Sfoglia il codice sorgente

fix: add return value for GM_addStyle

close #217
Gerald 8 anni fa
parent
commit
a18106ad7b
2 ha cambiato i file con 35 aggiunte e 3 eliminazioni
  1. 6 1
      src/injected/content/index.js
  2. 29 2
      src/injected/web/index.js

+ 6 - 1
src/injected/content/index.js

@@ -1,4 +1,5 @@
 import { isFirefox } from 'src/common/ua';
+import { getUniqId } from 'src/common';
 import { bindEvents, sendMessage, inject, attachFunction } from '../utils';
 import bridge from './bridge';
 import { tabOpen, tabClose, tabClosed } from './tabs';
@@ -82,12 +83,16 @@ const handlers = {
     if (IS_TOP) menus.push(data);
     getPopup();
   },
-  AddStyle(css) {
+  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);
     }
+    bridge.post({ cmd: 'Callback', data: { callbackId, payload: styleId } });
   },
   Notification: onNotificationCreate,
   SetClipboard(data) {

+ 29 - 2
src/injected/web/index.js

@@ -24,6 +24,7 @@ export default function initialize(webId, contentId, props) {
 const store = {
   commands: {},
   values: {},
+  callbacks: {},
 };
 
 const handlers = {
@@ -32,6 +33,10 @@ const handlers = {
     const func = store.commands[data];
     if (func) func();
   },
+  Callback({ callbackId, payload }) {
+    const func = store.callbacks[callbackId];
+    if (func) func(payload);
+  },
   GotRequestId: onRequestStart,
   HttpRequested: onRequestCallback,
   TabClosed: onTabClosed,
@@ -48,6 +53,15 @@ const handlers = {
   },
 };
 
+function registerCallback(callback) {
+  const callbackId = getUniqId('VMcb');
+  store.callbacks[callbackId] = payload => {
+    callback(payload);
+    delete store.callbacks[callbackId];
+  };
+  return callbackId;
+}
+
 function onHandle(obj) {
   const handle = handlers[obj.cmd];
   if (handle) handle(obj.data);
@@ -262,8 +276,21 @@ function wrapGM(script, code, cache) {
       },
     },
     GM_addStyle: {
-      value(data) {
-        bridge.post({ cmd: 'AddStyle', data });
+      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 callbacks.push(callback);
+          },
+        };
       },
     },
     GM_log: {