-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
69 lines (54 loc) · 2.31 KB
/
background.js
File metadata and controls
69 lines (54 loc) · 2.31 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
// MV3 service worker background script
// In MV3, the service worker can be suspended at any time, so we keep a small
// in-memory cache AND persist per-tab icon state in storage.session (if available).
const ICON_DEFAULT = 'icons/inactive.png';
// Prefer storage.session (not persisted across browser restarts) for tab state.
// Fallback to storage.local if session isn't available in the current environment.
const tabStateStorage = (chrome.storage && chrome.storage.session) ? chrome.storage.session : chrome.storage.local;
const iconCache = new Map(); // tabId -> icon filename, e.g. 'next.png'
function setTabIcon(tabId, iconFile) {
const path = 'icons/' + iconFile;
chrome.action.setIcon({ tabId, path });
}
async function rememberTabIcon(tabId, iconFile) {
iconCache.set(tabId, iconFile);
await tabStateStorage.set({ ['page_turner_icon_' + tabId]: iconFile });
}
async function recallTabIcon(tabId) {
if (iconCache.has(tabId)) return iconCache.get(tabId);
const key = 'page_turner_icon_' + tabId;
const data = await tabStateStorage.get(key);
const iconFile = data[key];
if (iconFile) iconCache.set(tabId, iconFile);
return iconFile;
}
// Messages from the content script tell us what icon to show for the current tab.
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (!request || !request.icon) return;
const tabId = sender && sender.tab && sender.tab.id;
if (typeof tabId !== 'number') return;
// Don't change extension icon when pages are prerendered.
// In MV3, sender.tab.active is usually available; if not, we still remember state.
const isActive = sender.tab && sender.tab.active === true;
(async () => {
if (isActive) setTabIcon(tabId, request.icon);
await rememberTabIcon(tabId, request.icon);
})();
// No async response needed.
});
// When user switches tabs, restore the last-known icon for that tab (or default).
chrome.tabs.onActivated.addListener(({ tabId }) => {
(async () => {
const iconFile = await recallTabIcon(tabId);
if (iconFile) {
setTabIcon(tabId, iconFile);
} else {
chrome.action.setIcon({ tabId, path: ICON_DEFAULT });
}
})();
});
// Avoid storing icon data for closed tabs.
chrome.tabs.onRemoved.addListener((tabId) => {
iconCache.delete(tabId);
tabStateStorage.remove('page_turner_icon_' + tabId);
});