Browse Source

refactor: use safe calls in AddStyle

tophf 6 years ago
parent
commit
6a97100f1d
2 changed files with 10 additions and 7 deletions
  1. 2 4
      src/injected/content/index.js
  2. 8 3
      src/injected/content/inject.js

+ 2 - 4
src/injected/content/index.js

@@ -6,7 +6,7 @@ import {
 } from '../utils/helpers';
 } from '../utils/helpers';
 import bridge from './bridge';
 import bridge from './bridge';
 import './clipboard';
 import './clipboard';
-import { injectPageSandbox, injectScripts } from './inject';
+import { appendToRoot, injectPageSandbox, injectScripts } from './inject';
 import './notifications';
 import './notifications';
 import './requests';
 import './requests';
 import './tabs';
 import './tabs';
@@ -81,9 +81,7 @@ bridge.addHandlers({
     const style = document::createElementNS(NS_HTML, 'style');
     const style = document::createElementNS(NS_HTML, 'style');
     style::setAttribute('id', styleId);
     style::setAttribute('id', styleId);
     style::append(css);
     style::append(css);
-    // DOM spec allows any elements under documentElement
-    // https://dom.spec.whatwg.org/#node-trees
-    (document.head || document.documentElement)::append(style);
+    appendToRoot(style);
     return styleId;
     return styleId;
   },
   },
   CheckScript: sendCmd,
   CheckScript: sendCmd,

+ 8 - 3
src/injected/content/inject.js

@@ -125,9 +125,14 @@ function inject(code, sourceUrl) {
     ...typeof code === 'string' ? [code] : code,
     ...typeof code === 'string' ? [code] : code,
     ...sourceUrl ? ['\n//# sourceURL=', sourceUrl] : [],
     ...sourceUrl ? ['\n//# sourceURL=', sourceUrl] : [],
   );
   );
-  const root = document::getHead() || document::getDocElem();
   // When using declarativeContent there's no documentElement so we'll append to `document`
   // When using declarativeContent there's no documentElement so we'll append to `document`
-  if (root) root::appendChild(script);
-  else document::appendChild(script);
+  if (!appendToRoot(script)) document::appendChild(script);
   script::remove();
   script::remove();
 }
 }
+
+export function appendToRoot(node) {
+  // DOM spec allows any elements under documentElement
+  // https://dom.spec.whatwg.org/#node-trees
+  const root = document::getHead() || document::getDocElem();
+  return root && root::appendChild(node);
+}