-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathcontent.js
More file actions
42 lines (37 loc) · 1.55 KB
/
content.js
File metadata and controls
42 lines (37 loc) · 1.55 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
/** @type {BroadcastChannel} */
let channel
/** @type {Set<string>} */
let configKeys
window.addEventListener('message', (event) => {
if (event.source !== window) return
if (event.data.type != 'init' || !event.data.channelName || !event.data.configKeys) return
channel = new BroadcastChannel(event.data.channelName)
configKeys = new Set(event.data.configKeys)
channel.addEventListener('message', storeConfigChangesFromPageScript)
chrome.storage.local.get((storedConfig) => {
let siteConfig = Object.fromEntries(
Object.entries(storedConfig).filter(([key]) => configKeys.has(key))
)
chrome.storage.local.onChanged.addListener(onStorageChanged)
channel.postMessage({type: 'initial', siteConfig})
})
})
/** @param {{[key: string]: chrome.storage.StorageChange}} storageChanges */
function onStorageChanged(storageChanges) {
/** @type {Partial<import("./types").SiteConfig>} */
let siteConfig = Object.fromEntries(
Object.entries(storageChanges)
.filter(([key]) => configKeys.has(key))
.map(([key, {newValue}]) => [key, newValue])
)
// Ignore storage changes which aren't relevant to the page script
if (Object.keys(siteConfig).length == 0) return
channel.postMessage({type: 'change', siteConfig})
}
/** @param {MessageEvent<Partial<import("./types").OptionsConfig>>} message */
function storeConfigChangesFromPageScript({data: changes}) {
chrome.storage.local.onChanged.removeListener(onStorageChanged)
chrome.storage.local.set(changes, () => {
chrome.storage.local.onChanged.addListener(onStorageChanged)
})
}