|
1 | | -export const injectScripts = (scripts: string[], cb?: () => void) => { |
2 | | - let injected = 0; |
3 | | - scripts.forEach(s => |
4 | | - injectScript(chrome.runtime.getURL(s), () => { |
5 | | - injected++; |
6 | | - if (injected === scripts.length && cb) { |
7 | | - cb(); |
8 | | - } |
| 1 | +const loadScripts = (urls: string[]) => { |
| 2 | + return urls |
| 3 | + .map((url, idx) => { |
| 4 | + return ` |
| 5 | + const script${idx} = document.constructor.prototype.createElement.call(document, 'script'); |
| 6 | + script${idx}.src = getScriptName("${url}"); |
| 7 | + document.documentElement.appendChild(script${idx}); |
| 8 | + script${idx}.parentNode.removeChild(script${idx}); |
| 9 | + `; |
9 | 10 | }) |
10 | | - ); |
| 11 | + .join('\n'); |
11 | 12 | }; |
12 | 13 |
|
13 | | -const injectScript = (scriptName: string, cb: () => void) => { |
14 | | - const src = ` |
15 | | - (function() { |
16 | | - var script = document.constructor.prototype.createElement.call(document, 'script'); |
17 | | - script.src = "${scriptName}"; |
18 | | - document.documentElement.appendChild(script); |
19 | | - script.parentNode.removeChild(script); |
20 | | - })() |
| 14 | +let loaded = false; |
| 15 | +export const injectScripts = (urls: string[], cb?: () => void) => { |
| 16 | + if (loaded) { |
| 17 | + // Not throwing a hard error here, because we don't want to stop the |
| 18 | + // execution when folks are not using Trusted Types or when they have |
| 19 | + // allowed redeclaration of a security policy. |
| 20 | + console.error('Trying to reinject scripts'); |
| 21 | + } |
| 22 | + loaded = true; |
| 23 | + urls = urls.map((s) => chrome.runtime.getURL(s)); |
| 24 | + const script = ` |
| 25 | + (function () { |
| 26 | + let policy = null; |
| 27 | + if (window.trustedTypes && window.trustedTypes.createPolicy) { |
| 28 | + policy = window.trustedTypes.createPolicy('angular#devtools', { |
| 29 | + createScriptURL: url => ${JSON.stringify(urls)}.indexOf(url) >= 0 ? url : null |
| 30 | + }); |
| 31 | + } |
| 32 | + const getScriptName = name => policy ? policy.createScriptURL(name) : name; |
| 33 | + ${loadScripts(urls)} |
| 34 | + })(); |
21 | 35 | `; |
22 | | - chrome.devtools.inspectedWindow.eval(src, (_, err) => { |
| 36 | + chrome.devtools.inspectedWindow.eval(script, (_, err) => { |
23 | 37 | if (err) { |
24 | 38 | console.log(err); |
25 | 39 | } |
26 | | - cb(); |
| 40 | + cb?.(); |
27 | 41 | }); |
28 | 42 | }; |
0 commit comments