瀏覽代碼

return the element immediately in GM_addStyle (#620)

.then() is still present on the returned value for compatibility with VM's 2017-2019 behavior
tophf 6 年之前
父節點
當前提交
a8a4e0167a
共有 2 個文件被更改,包括 12 次插入16 次删除
  1. 7 8
      src/injected/content/index.js
  2. 5 8
      src/injected/web/index.js

+ 7 - 8
src/injected/content/index.js

@@ -194,14 +194,13 @@ const handlers = {
     getPopup();
   },
   AddStyle({ css, callbackId }) {
-    let styleId = null;
-    if (document.head) {
-      styleId = getUniqId('VMst');
-      const style = document.createElement('style');
-      style.id = styleId;
-      style.textContent = css;
-      document.head.appendChild(style);
-    }
+    const styleId = getUniqId('VMst');
+    const style = document.createElement('style');
+    style.id = styleId;
+    style.textContent = css;
+    // DOM spec allows any elements under documentElement
+    // https://dom.spec.whatwg.org/#node-trees
+    (document.head || document.documentElement).appendChild(style);
     bridge.post({ cmd: 'Callback', data: { callbackId, payload: styleId } });
   },
   Notification: onNotificationCreate,

+ 5 - 8
src/injected/web/index.js

@@ -285,20 +285,17 @@ function wrapGM(script, code, cache, unsafeWindow) {
     },
     GM_addStyle: {
       value(css) {
-        const callbacks = [];
         let el = false;
         const callbackId = registerCallback((styleId) => {
           el = document.getElementById(styleId);
-          callbacks.splice().forEach(callback => callback(el));
         });
         bridge.post({ cmd: 'AddStyle', data: { css, callbackId } });
         // Mock a Promise without the need for polyfill
-        return {
-          then(callback) {
-            if (el !== false) callback(el);
-            else push(callbacks, callback);
-          },
-        };
+        // It's not actually necessary because DOM messaging is synchronous
+        // but we keep it for compatibility with VM's 2017-2019 behavior
+        // https://github.com/violentmonkey/violentmonkey/issues/217
+        el.then = callback => callback(el);
+        return el;
       },
     },
     GM_log: {