-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
58 lines (50 loc) · 1.82 KB
/
Copy pathbackground.js
File metadata and controls
58 lines (50 loc) · 1.82 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
/*
* background.js — MV3 service worker.
*
* Sole job: inject the in-page overlay on demand (from the popup) and report
* its visibility. Injection is triggered only by an explicit user action and
* targets the tab the user is looking at (activeTab), so the extension touches
* a page only when asked.
*/
'use strict';
const OVERLAY_FILES = ['lib/format.js', 'lib/priority.js', 'content/overlay.js'];
/** Read the overlay's current visibility flag from the page (isolated world). */
function readOverlayVisible() {
return typeof window.__wfiOverlayVisible === 'boolean' ? window.__wfiOverlayVisible : false;
}
async function injectAndToggle(tabId) {
// Re-running overlay.js is idempotent: it toggles if already present.
await chrome.scripting.executeScript({ target: { tabId }, files: OVERLAY_FILES });
const res = await chrome.scripting.executeScript({
target: { tabId },
func: readOverlayVisible,
});
return !!(res && res[0] && res[0].result);
}
async function readState(tabId) {
try {
const res = await chrome.scripting.executeScript({
target: { tabId },
func: readOverlayVisible,
});
return !!(res && res[0] && res[0].result);
} catch (e) {
return false;
}
}
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (!msg || !msg.type) return false;
if (msg.type === 'WFI_TOGGLE_OVERLAY') {
injectAndToggle(msg.tabId)
.then((visible) => sendResponse({ ok: true, visible }))
.catch((err) => sendResponse({ ok: false, error: String(err && err.message ? err.message : err) }));
return true; // async response
}
if (msg.type === 'WFI_OVERLAY_STATE') {
readState(msg.tabId)
.then((visible) => sendResponse({ ok: true, visible }))
.catch(() => sendResponse({ ok: true, visible: false }));
return true;
}
return false;
});