-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
155 lines (136 loc) · 4.74 KB
/
Copy pathbackground.js
File metadata and controls
155 lines (136 loc) · 4.74 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
/**
* background.js - Service Worker v1.3.0
* Handles tab capture, caching, message routing
*/
const cache = {
data: new Map(),
capturing: new Map(),
timers: new Map(),
size: 0,
LIMIT: 200,
MAX_MEM: 20 << 20,
_saveTimer: null,
sizeOf: d => d ? Math.floor(d.length * 0.75) : 0,
async load() {
const { vts_thumbnails: s = {} } = await chrome.storage.session.get('vts_thumbnails').catch(() => ({}));
this.data.clear(), this.size = 0;
for (const [id, d] of Object.entries(s)) {
if (!id.startsWith('_')) this.data.set(+id, d), this.size += this.sizeOf(d);
}
},
save() {
if (this._saveTimer) clearTimeout(this._saveTimer);
this._saveTimer = setTimeout(() => {
chrome.storage.session.set({ vts_thumbnails: Object.fromEntries(this.data) }).catch(() => {});
this._saveTimer = null;
}, 1000);
},
evict() {
while (this.data.size > this.LIMIT || this.size > this.MAX_MEM) {
const [k, d] = this.data.entries().next().value || [];
this.size -= this.sizeOf(d), this.data.delete(k);
}
},
set(id, d) {
if (!d) return;
this.size -= this.sizeOf(this.data.get(id));
this.data.set(id, d), this.size += this.sizeOf(d);
this.evict(), this.save();
},
del(id) {
this.size -= this.sizeOf(this.data.get(id));
this.data.delete(id);
this.capturing.delete(id);
this.timers.delete(id);
chrome.alarms.clear(`c_${id}`).catch(() => {});
this.save();
}
};
const isAllowed = url => url && !['chrome://', 'edge://', 'about:', 'chrome-extension://', 'file://'].some(p => url.startsWith(p));
async function capture(tabId, windowId) {
const now = Date.now(), c = cache.capturing.get(tabId);
if (c && now - c.t < 5000) return c.p;
const p = chrome.tabs.captureVisibleTab(windowId, { format: 'jpeg', quality: 45 })
.then(d => (cache.set(tabId, d), d))
.catch(() => null)
.finally(() => cache.capturing.delete(tabId));
cache.capturing.set(tabId, { p, t: now });
return p;
}
const router = {
async getTabsAndCapture({ tab }) {
let wid = tab?.windowId;
let captureId = tab?.id;
if (!wid) {
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!activeTab) return { tabs: [] };
wid = activeTab.windowId;
captureId = activeTab.id;
}
const [tabs] = await Promise.all([
chrome.tabs.query({ windowId: wid }),
captureId ? capture(captureId, wid) : null
]);
return {
tabs: tabs.map(t => ({
id: t.id, title: t.title || '加载中...', favIconUrl: t.favIconUrl || '',
active: t.active, thumbnail: cache.data.get(t.id)
}))
};
},
async switchTab({ tabId }) {
try { await chrome.tabs.update(tabId, { active: true }); return { ok: true }; }
catch (e) { return { ok: false, error: e.message }; }
},
async closeTab({ tabId }) {
try {
await chrome.tabs.remove(tabId);
cache.del(tabId);
return { ok: true };
} catch (e) { return { ok: false, error: e.message }; }
}
};
chrome.alarms.onAlarm.addListener(async ({ name }) => {
if (!name.startsWith('c_')) return;
const id = +name.slice(2), wid = cache.timers.get(id);
if (!wid) return;
const t = await chrome.tabs.get(id).catch(() => null);
t?.active && isAllowed(t.url) ? await capture(id, wid) : (chrome.alarms.clear(name), cache.timers.delete(id));
});
chrome.tabs.onActivated.addListener(async ({ tabId, windowId }) => {
const t = await chrome.tabs.get(tabId).catch(() => null);
if (t && isAllowed(t.url)) {
await capture(tabId, windowId);
chrome.alarms.create(`c_${tabId}`, { periodInMinutes: 10 });
cache.timers.set(tabId, windowId);
}
});
chrome.tabs.onUpdated.addListener(async (id, { status }, t) => {
if (status === 'complete' && t?.active && isAllowed(t.url)) {
await capture(id, t.windowId);
chrome.alarms.create(`c_${id}`, { periodInMinutes: 10 });
cache.timers.set(id, t.windowId);
}
});
chrome.tabs.onRemoved.addListener(id => {
cache.del(id);
});
chrome.commands.onCommand.addListener(cmd => {
if (cmd !== 'open-overlay' && cmd !== 'navigate-up') return;
chrome.tabs.query({ active: true, currentWindow: true }, ([t]) => {
if (!t?.id || !isAllowed(t.url)) return;
const action = cmd === 'navigate-up' ? 'navigateUp' : 'trigger';
chrome.tabs.sendMessage(t.id, { action }, r => {
if (chrome.runtime.lastError) {
chrome.scripting.executeScript({ target: { tabId: t.id }, files: ['content-script.js'] })
.then(() => setTimeout(() => chrome.tabs.sendMessage(t.id, { action }), 100));
}
});
});
});
chrome.runtime.onMessage.addListener((msg, sender, send) => {
const h = router[msg.action];
if (h) h({ ...msg, tab: sender.tab }).then(send).catch(() => send({}));
return true;
});
cache.load();