forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent-script-manager.ts
More file actions
98 lines (87 loc) · 3.79 KB
/
Copy pathcontent-script-manager.ts
File metadata and controls
98 lines (87 loc) · 3.79 KB
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
import {logWarn} from './utils/log';
declare const __CHROMIUM_MV3__: boolean;
enum ContentScriptManagerState {
UNKNOWN,
REGISTERING,
REGISTERED,
NOTREGISTERED
}
export default class ContentScriptManager {
/**
* TODO: migrate to using promises directly instead of wrapping callbacks.
* Docs say that Promises are not supported yet, but in practice they appear
* to be supported already...
*/
static state: ContentScriptManagerState;
static async registerScripts(updateContentScripts: () => Promise<void>): Promise<void> {
if (!__CHROMIUM_MV3__) {
logWarn('ContentScriptManager is useful only within MV3 builds.');
return;
}
if (ContentScriptManager.state === ContentScriptManagerState.REGISTERING ||
ContentScriptManager.state === ContentScriptManagerState.REGISTERED) {
return;
}
ContentScriptManager.state = ContentScriptManagerState.REGISTERING;
return new Promise<void>((resolve) =>
chrome.scripting.getRegisteredContentScripts(
{ids: ['stylesheet-proxy', 'content-scripts']},
(scripts) => {
if (scripts.length === 2) {
ContentScriptManager.state = ContentScriptManagerState.REGISTERED;
resolve();
} else {
ContentScriptManager.state = ContentScriptManagerState.NOTREGISTERED;
updateContentScripts();
// Note: This API does not support registering injections into about:blank.
// That is, there is no alternative to InjectDetails.matchAboutBlank
// or static manifest declaration 'match_about_blank'.
// Therefore we need to also specify these scripts in manifest.json
// just for about:blank.
chrome.scripting.registerContentScripts([
{
id: 'stylesheet-proxy',
js: [
'inject/proxy.js',
],
runAt: 'document_start',
persistAcrossSessions: true,
matches: [
'<all_urls>',
],
allFrames: true,
world: 'MAIN',
},
{
id: 'content-scripts',
js: [
'inject/fallback.js',
'inject/index.js',
],
runAt: 'document_start',
persistAcrossSessions: true,
matches: [
'<all_urls>',
],
allFrames: true,
world: 'ISOLATED',
},
], resolve);
}
}
));
}
static async unregisterScripts(): Promise<void> {
if (!__CHROMIUM_MV3__) {
logWarn('ContentScriptManager is useful only within MV3 builds.');
return;
}
if (ContentScriptManager.state === ContentScriptManagerState.NOTREGISTERED) {
return;
}
return new Promise<void>((resolve) => chrome.scripting.unregisterContentScripts(() => {
ContentScriptManager.state = ContentScriptManagerState.NOTREGISTERED;
resolve();
}));
}
}