-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
174 lines (150 loc) · 4.48 KB
/
Copy pathbackground.js
File metadata and controls
174 lines (150 loc) · 4.48 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
(() => {
"use strict";
const DEFAULT_SITES = Object.freeze({
"linkedin.com": true,
"x.com": true,
"twitter.com": true,
});
const DEFAULT_DOMAINS = new Set(Object.keys(DEFAULT_SITES));
const VALID_MODES = new Set(["standard", "constrained"]);
const SCRIPT_PREFIX = "egodim-";
function normalizeState(value = {}) {
const storedSites =
value.sites &&
typeof value.sites === "object" &&
!Array.isArray(value.sites)
? value.sites
: {};
const sites = { ...DEFAULT_SITES };
for (const [domain, enabled] of Object.entries(storedSites)) {
if (typeof enabled === "boolean") {
sites[domain] = enabled;
}
}
return {
mode: VALID_MODES.has(value.mode) ? value.mode : "standard",
sites,
};
}
function isValidStoredDomain(domain) {
if (domain === "localhost") {
return true;
}
if (
typeof domain !== "string" ||
domain.length > 253 ||
!domain.includes(".")
) {
return false;
}
return domain
.split(".")
.every((label) => /^(?!-)[a-z0-9-]{1,63}(?<!-)$/.test(label));
}
function scriptFor(domain) {
return {
id: `${SCRIPT_PREFIX}${domain}`,
matches: [`*://*.${domain}/*`],
css: ["content.css"],
js: ["content.js"],
runAt: "document_start",
allFrames: true,
persistAcrossSessions: true,
};
}
async function ensureStoredState() {
const stored = await chrome.storage.sync.get(["enabled", "mode", "sites"]);
const normalized = normalizeState(stored);
const patch = {};
if (!VALID_MODES.has(stored.mode)) {
patch.mode = normalized.mode;
}
const storedSites =
stored.sites &&
typeof stored.sites === "object" &&
!Array.isArray(stored.sites)
? stored.sites
: {};
const sitesNeedRepair =
Object.keys(DEFAULT_SITES).some(
(domain) => typeof storedSites[domain] !== "boolean",
) ||
Object.entries(storedSites).some(
([, enabled]) => typeof enabled !== "boolean",
);
if (sitesNeedRepair) {
patch.sites = normalized.sites;
}
if (Object.keys(patch).length > 0) {
await chrome.storage.sync.set(patch);
}
if (Object.hasOwn(stored, "enabled")) {
await chrome.storage.sync.remove("enabled");
}
return normalized;
}
async function reconcileDynamicScripts(state) {
const registrations = await chrome.scripting.getRegisteredContentScripts();
const managed = new Map(
registrations
.filter(({ id }) => id.startsWith(SCRIPT_PREFIX))
.map((registration) => [registration.id, registration]),
);
const desiredDomains = Object.keys(state.sites).filter(
(domain) => !DEFAULT_DOMAINS.has(domain) && isValidStoredDomain(domain),
);
const desiredIds = new Set(
desiredDomains.map((domain) => `${SCRIPT_PREFIX}${domain}`),
);
const staleIds = [...managed.keys()].filter((id) => !desiredIds.has(id));
if (staleIds.length > 0) {
await chrome.scripting.unregisterContentScripts({ ids: staleIds });
}
for (const domain of desiredDomains) {
const descriptor = scriptFor(domain);
const hasPermission = await chrome.permissions.contains({
origins: descriptor.matches,
});
if (!hasPermission) {
continue;
}
if (managed.has(descriptor.id)) {
await chrome.scripting.updateContentScripts([descriptor]);
} else {
await chrome.scripting.registerContentScripts([descriptor]);
}
}
}
async function initialize() {
const state = await ensureStoredState();
await Promise.all([
chrome.action.setBadgeText({ text: "" }),
reconcileDynamicScripts(state),
]);
}
function initializeSafely() {
initialize().catch(() => {
// A missing optional host permission can make a synced dynamic site
// temporarily unavailable. The popup can restore it via a user gesture.
});
}
chrome.runtime.onInstalled.addListener(initializeSafely);
chrome.runtime.onStartup.addListener(initializeSafely);
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName !== "sync") {
return;
}
if (Object.hasOwn(changes, "sites")) {
ensureStoredState()
.then(reconcileDynamicScripts)
.catch(() => {});
}
});
if (globalThis.__EGODIM_TEST__) {
globalThis.__EGODIM_TEST__.background = {
isValidStoredDomain,
normalizeState,
scriptFor,
};
}
})();