forked from fregante/content-scripts-register-polyfill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
107 lines (91 loc) · 2.63 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/// <reference path="./globals.d.ts" />
import {patternToRegex} from 'webext-patterns';
// @ts-expect-error
async function p<T>(fn, ...args): Promise<T> {
return new Promise((resolve, reject) => {
// @ts-expect-error
fn(...args, result => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve(result);
}
});
});
}
async function isOriginPermitted(url: string): Promise<boolean> {
return p(chrome.permissions.contains, {
origins: [new URL(url).origin + '/*']
});
}
async function wasPreviouslyLoaded(tabId: number, loadCheck: string): Promise<boolean> {
const result = await p<boolean[]>(chrome.tabs.executeScript, tabId, {
code: loadCheck,
runAt: 'document_start'
});
return result?.[0];
}
if (typeof chrome === 'object' && !chrome.contentScripts) {
chrome.contentScripts = {
// The callback is only used by webextension-polyfill
async register(contentScriptOptions, callback) {
const {
js = [],
css = [],
allFrames,
matchAboutBlank,
matches,
runAt
} = contentScriptOptions;
// Injectable code; it sets a `true` property on `document` with the hash of the files as key.
const loadCheck = `document[${JSON.stringify(JSON.stringify({js, css}))}]`;
const matchesRegex = patternToRegex(...matches);
const listener = async (tabId: number, {status}: chrome.tabs.TabChangeInfo): Promise<void> => {
if (status !== 'loading') {
return;
}
const {url} = await p(chrome.tabs.get, tabId);
if (
!url || // No URL = no permission;
!matchesRegex.test(url) || // Manual `matches` glob matching
!await isOriginPermitted(url) || // Permissions check
await wasPreviouslyLoaded(tabId, loadCheck) // Double-injection avoidance
) {
return;
}
for (const file of css) {
chrome.tabs.insertCSS(tabId, {
...file,
matchAboutBlank,
allFrames,
runAt: runAt ?? 'document_start' // CSS should prefer `document_start` when unspecified
});
}
for (const file of js) {
chrome.tabs.executeScript(tabId, {
...file,
matchAboutBlank,
allFrames,
runAt
});
}
// Mark as loaded
chrome.tabs.executeScript(tabId, {
code: `${loadCheck} = true`,
runAt: 'document_start',
allFrames
});
};
chrome.tabs.onUpdated.addListener(listener);
const registeredContentScript = {
async unregister() {
return p(chrome.tabs.onUpdated.removeListener.bind(chrome.tabs.onUpdated), listener);
}
};
if (typeof callback === 'function') {
callback(registeredContentScript);
}
return Promise.resolve(registeredContentScript);
}
};
}