Skip to content
This repository was archived by the owner on Jan 27, 2022. It is now read-only.

Commit d903513

Browse files
committed
feat: support trusted types for script injection
1 parent abee199 commit d903513

File tree

1 file changed

+33
-19
lines changed

1 file changed

+33
-19
lines changed
Lines changed: 33 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,42 @@
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+
`;
910
})
10-
);
11+
.join('\n');
1112
};
1213

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+
})();
2135
`;
22-
chrome.devtools.inspectedWindow.eval(src, (_, err) => {
36+
chrome.devtools.inspectedWindow.eval(script, (_, err) => {
2337
if (err) {
2438
console.log(err);
2539
}
26-
cb();
40+
cb?.();
2741
});
2842
};

0 commit comments

Comments
 (0)