forked from Wielding/kagi-focused-ntp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
627 lines (559 loc) · 25.2 KB
/
Copy pathbackground.js
File metadata and controls
627 lines (559 loc) · 25.2 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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
const ALL_CATEGORIES = [
'ai', 'science', 'programming', 'diy', 'tech', 'hardware', 'infra', 'web',
'health', 'art', 'essays', 'humanities', 'retro', 'photography', 'culture', 'gaming',
'society', 'life', 'food', 'travel', 'politics', 'economy'
];
const ALL_FEEDS = ['blogs', 'appreciated', 'youtube', 'github', 'comics'];
function decodeXmlEntities(s) {
return s
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/"/g, '"').replace(/'/g, "'")
.replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCharCode(parseInt(h, 16)))
.replace(/&#(\d+);/g, (_, c) => String.fromCharCode(+c));
}
const FEED_ENDPOINTS = {
blogs: 'https://kagi.com/api/v1/smallweb/feed/?nso',
youtube: 'https://kagi.com/api/v1/smallweb/feed/?yt',
github: 'https://kagi.com/api/v1/smallweb/feed/?gh',
comics: 'https://kagi.com/api/v1/smallweb/feed/?comic',
appreciated: 'https://kagi.com/smallweb/appreciated'
};
const SMALLWEB_BASE = 'https://kagi.com/smallweb';
// Feed entries (especially "appreciated") may wrap the real URL as
// https://kagi.com/smallweb?url=ACTUAL — strip the wrapper so we
// load the article directly and never show the /smallweb frame.
function unwrapSmallwebUrl(url) {
try {
const u = new URL(url);
if (u.hostname === 'kagi.com' && u.pathname === '/smallweb') {
const inner = u.searchParams.get('url');
if (inner && /^https?:\/\//.test(inner)) return inner;
}
} catch (e) {}
return url;
}
// ═══════════════════════════════════════
// FEED CACHING
// ═══════════════════════════════════════
function parseAtomEntries(xml) {
const entries = [];
let pos = 0;
while (true) {
const start = xml.indexOf('<entry', pos);
if (start === -1) break;
const end = xml.indexOf('</entry>', start);
if (end === -1) break;
const block = xml.slice(start, end);
pos = end + 8;
// Prefer rel="alternate" links (the actual article) over rel="self" (the feed URL)
const altHref = block.match(/rel="alternate"[^>]*href="(https:\/\/[^"]+)"/)
|| block.match(/href="(https:\/\/[^"]+)"[^>]*rel="alternate"/);
const href = altHref || block.match(/href="(https:\/\/[^"]+)"/);
const titleTag = block.match(/<title[^>]*>([^<]+)<\/title>/);
const cats = [];
const catRe = /<category[^>]+term="([^"]+)"/g;
let catMatch;
while ((catMatch = catRe.exec(block))) cats.push(catMatch[1]);
if (href) {
entries.push({
title: decodeXmlEntities(titleTag?.[1] || 'Untitled'),
url: unwrapSmallwebUrl(href[1]),
categories: cats
});
}
}
return entries;
}
async function getRandomFeedEntry(feedName) {
const CACHE_KEY = 'feedData';
const THREE_HOURS = 3 * 60 * 60 * 1000;
const stored = await chrome.storage.local.get(CACHE_KEY);
const all = stored[CACHE_KEY] || {};
const slot = all[feedName];
let entries;
if (slot && slot.entries.length > 0 && (Date.now() - slot.fetchedAt) < THREE_HOURS) {
entries = slot.entries;
} else {
try {
const res = await fetch(FEED_ENDPOINTS[feedName]);
if (!res.ok) throw new Error(res.status);
entries = parseAtomEntries(await res.text());
all[feedName] = { entries, fetchedAt: Date.now() };
await chrome.storage.local.set({ [CACHE_KEY]: all });
} catch (e) {
entries = slot?.entries || [];
}
}
if (entries.length === 0) return null;
const entry = entries[Math.floor(Math.random() * entries.length)];
// Unwrap cached entries that predate the parse-time fix
entry.url = unwrapSmallwebUrl(entry.url);
return entry;
}
// ═══════════════════════════════════════
// IFRAME PREPARATION
// ═══════════════════════════════════════
// YouTube embeds don't work from chrome-extension:// origins directly,
// but our youtube.html wrapper page hosts the embed from our extension origin.
function youTubeVideoId(url) {
try {
const u = new URL(url);
if (u.hostname.includes('youtube.com')) {
return u.searchParams.get('v') || u.pathname.match(/\/(?:shorts|embed)\/([^/?]+)/)?.[1];
}
if (u.hostname === 'youtu.be') {
return u.pathname.slice(1).split('/')[0];
}
} catch (e) {}
return null;
}
// One function for all header stripping. Uses tabId as rule ID
// so each tab gets its own rule — no collisions, no tracking Maps.
// URLs that look like feeds/XML — skip content script injection so the
// browser can render them natively (XML tree view or XSLT stylesheet).
function isXmlUrl(url) {
const path = new URL(url).pathname.toLowerCase();
return /\.(xml|rss|atom|feed)$/.test(path) || /\/(feed|rss|atom)\/?$/.test(path);
}
async function prepareIframe(url, tabId) {
const urlObj = new URL(url);
if (urlObj.hostname === 'kagi.com') return; // static rules.json handles kagi.com
const scriptId = 'block-focus-' + tabId;
await chrome.scripting.unregisterContentScripts({ ids: [scriptId] }).catch(() => {});
await chrome.declarativeNetRequest.updateSessionRules({
removeRuleIds: [tabId],
addRules: [{
id: tabId,
priority: 1,
action: {
type: 'modifyHeaders',
responseHeaders: [
{ header: 'X-Frame-Options', operation: 'remove' },
{ header: 'Content-Security-Policy', operation: 'set', value: "default-src * data: blob: 'unsafe-inline' 'unsafe-eval'; object-src 'none';" }
]
},
condition: {
urlFilter: '||' + urlObj.hostname,
resourceTypes: ['sub_frame'],
tabIds: [tabId]
}
}]
});
// Skip content script for XML/RSS — injecting into XML documents
// destroys the browser's native XML tree view and XSLT rendering.
if (!isXmlUrl(url)) {
await chrome.scripting.registerContentScripts([{
id: scriptId,
matches: [urlObj.origin + '/*'],
js: ['block-focus.js'],
runAt: 'document_start',
world: 'MAIN',
allFrames: true
}]);
}
}
function cleanupTab(tabId) {
chrome.storage.session.remove('articleUrl_' + tabId);
chrome.declarativeNetRequest.updateSessionRules({ removeRuleIds: [tabId] });
chrome.scripting.unregisterContentScripts({ ids: ['block-focus-' + tabId] }).catch(() => {});
setContextMenu(false);
}
// ═══════════════════════════════════════
// ARTICLE INFO (session storage — survives SW restarts)
// ═══════════════════════════════════════
async function setArticleInfo(tabId, url, title, source) {
await chrome.storage.session.set({ ['articleUrl_' + tabId]: { url, title, source } });
// Show context menu if this is the active tab
try {
const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (activeTab?.id === tabId) await setContextMenu(true);
} catch (e) {}
// Append to persistent history (max 50, dedup consecutive)
try {
const HISTORY_KEY = 'articleHistory';
const MAX = 100;
const stored = await chrome.storage.local.get(HISTORY_KEY);
const history = stored[HISTORY_KEY] || [];
if (history.length === 0 || history[0].url !== url) {
history.unshift({ url, title, source, timestamp: Date.now() });
if (history.length > MAX) history.length = MAX;
await chrome.storage.local.set({ [HISTORY_KEY]: history });
}
} catch (e) {}
}
async function getArticleInfo(tabId) {
const stored = await chrome.storage.session.get('articleUrl_' + tabId);
return stored['articleUrl_' + tabId] || null;
}
// ═══════════════════════════════════════
// CONTEXT MENU
// ═══════════════════════════════════════
function setContextMenu(visible) {
return new Promise(resolve => {
chrome.contextMenus.removeAll(() => {
if (visible) {
chrome.contextMenus.create({ id: 'bookmark-article', title: 'Bookmark this', contexts: ['page', 'frame', 'link'] });
chrome.contextMenus.create({ id: 'add-to-reading-list', title: 'Add to Reading List', contexts: ['page', 'frame', 'link'] });
chrome.contextMenus.create({ id: 'appreciate-post', title: 'Appreciate this', contexts: ['page', 'frame', 'link'] });
}
resolve();
});
});
}
// Show/hide context menu based on whether this tab has article info
async function updateContextMenuForTab(tabId) {
const info = await getArticleInfo(tabId);
await setContextMenu(!!info);
}
// ═══════════════════════════════════════
// BOOKMARKS & APPRECIATE
// ═══════════════════════════════════════
async function getOrCreateFolder(parentId, name) {
const children = await chrome.bookmarks.getChildren(parentId);
return children.find(b => b.title === name && !b.url)
|| await chrome.bookmarks.create({ parentId, title: name });
}
async function getBookmarkFolder(source) {
const tree = await chrome.bookmarks.getTree();
const root = tree[0].children;
// Look for existing Small Web folder in preferred order before creating one
const otherBookmarks = root.find(b => /other bookmarks/i.test(b.title));
const bookmarksBar = root.find(b => /bookmarks bar/i.test(b.title));
const searchOrder = [bookmarksBar, otherBookmarks, root[0]].filter(Boolean);
let swFolder = null;
for (const parent of searchOrder) {
const children = await chrome.bookmarks.getChildren(parent.id);
const found = children.find(b => b.title === 'Small Web' && !b.url);
if (found) { swFolder = found; break; }
}
if (!swFolder) {
const defaultParent = searchOrder[0];
swFolder = await chrome.bookmarks.create({ parentId: defaultParent.id, title: 'Small Web' });
}
if (!source) return swFolder;
// source is "cat/ai" or "feed/github" → create subfolders
const parts = source.split('/');
let folder = swFolder;
for (const part of parts) {
folder = await getOrCreateFolder(folder.id, part);
}
return folder;
}
async function appreciatePost(url) {
try {
const formData = new FormData();
formData.append('url', url);
formData.append('emoji', '\uD83D\uDC4D');
const response = await fetch(SMALLWEB_BASE + '/favorite', {
method: 'POST', body: formData, credentials: 'include'
});
return response.ok;
} catch (e) {
return false;
}
}
// ═══════════════════════════════════════
// EVENT LISTENERS
// ═══════════════════════════════════════
// Tab activated: update context menu from session storage
chrome.tabs.onActivated.addListener(({ tabId }) => {
updateContextMenuForTab(tabId);
});
// Tab closed: clean up everything for that tab
chrome.tabs.onRemoved.addListener((tabId) => {
cleanupTab(tabId);
});
// Top-level navigation: clean up stale state.
// For our own extension pages (NTP refresh), clear old article info so the
// new article gets recorded. For external pages, keep info if navigating
// to the article itself (e.g. YouTube card click).
chrome.webNavigation.onCommitted.addListener(async (details) => {
if (details.frameId === 0 && details.url.startsWith('chrome-extension://')) {
// NTP refresh — don't cleanup here; main.js reads the previous
// article info for back-button history, then the new article's
// setArticleInfo overwrites it naturally.
return;
}
if (details.frameId === 0) {
const info = await getArticleInfo(details.tabId);
if (info && info.url === details.url) {
// Keep article info + context menu when navigating to the article itself (e.g. YouTube card)
await setContextMenu(true);
} else {
cleanupTab(details.tabId);
}
}
});
// Category pages: discover the article inside kagi.com/smallweb
chrome.webNavigation.onCompleted.addListener(async (details) => {
if (!details.url.startsWith('https://kagi.com/smallweb')) return;
const tab = await chrome.tabs.get(details.tabId).catch(() => null);
if (!tab?.active) return;
const frames = await chrome.webNavigation.getAllFrames({ tabId: details.tabId });
const articleFrame = frames?.find(f =>
f.parentFrameId !== -1 &&
!f.url.startsWith('chrome-extension://') &&
!f.url.startsWith('https://kagi.com/smallweb') &&
!f.url.startsWith('about:')
);
if (!articleFrame) return;
let title = articleFrame.url;
try {
const results = await chrome.scripting.executeScript({
target: { tabId: details.tabId, frameIds: [articleFrame.frameId] },
func: () => document.title
});
if (results?.[0]?.result) title = results[0].result;
} catch (e) {}
// Extract category from the kagi.com/smallweb URL (e.g. ?cat=ai)
try {
const cat = new URL(details.url).searchParams.get('cat');
await setArticleInfo(details.tabId, articleFrame.url, title, cat ? 'cat/' + cat : null);
} catch (e) {
await setArticleInfo(details.tabId, articleFrame.url, title);
}
});
// ═══════════════════════════════════════
// CONTEXT MENU CLICK HANDLERS
// ═══════════════════════════════════════
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
const article = await getArticleInfo(tab.id);
if (info.menuItemId === 'bookmark-article') {
const folder = await getBookmarkFolder(article?.source);
if (info.linkUrl) {
await chrome.bookmarks.create({ parentId: folder.id, title: info.selectionText || info.linkUrl, url: info.linkUrl });
} else {
const url = article?.url || info.frameUrl || info.pageUrl;
const title = article?.title || url;
await chrome.bookmarks.create({ parentId: folder.id, title, url });
}
}
if (info.menuItemId === 'add-to-reading-list') {
const url = info.linkUrl || article?.url || info.frameUrl || info.pageUrl;
const title = info.selectionText || article?.title || url;
try { await chrome.readingList.addEntry({ url, title, hasBeenRead: false }); } catch (e) {}
}
if (info.menuItemId === 'appreciate-post') {
const url = info.linkUrl || article?.url || info.frameUrl || info.pageUrl;
if (url) await appreciatePost(url);
}
});
// ═══════════════════════════════════════
// MESSAGE HANDLER
// ═══════════════════════════════════════
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.action === 'restoreDefaultNTP' && sender.tab) {
chrome.tabs.update(sender.tab.id, { url: 'chrome://new-tab-page' });
}
// Combined: fetch feed entry + prepare iframe + cache article info
if (msg.action === 'loadFeedContent' && sender.tab) {
(async () => {
try {
const entry = await getRandomFeedEntry(msg.feed);
if (!entry) { sendResponse({ url: null }); return; }
await setArticleInfo(sender.tab.id, entry.url, entry.title, 'feed/' + msg.feed);
const ytId = youTubeVideoId(entry.url);
if (!ytId) {
await prepareIframe(entry.url, sender.tab.id);
}
console.log('[Kagi NTP] source: feed/' + msg.feed + ' | URL:', entry.url);
sendResponse({ url: entry.url, title: entry.title, youtube: !!ytId, videoId: ytId });
} catch (e) {
sendResponse({ url: null });
}
})();
return true;
}
// Category from blogs feed (direct article, no Kagi frame)
if (msg.action === 'loadCategoryFromFeed' && sender.tab) {
(async () => {
try {
const entry = await getRandomFeedEntry('blogs');
if (!entry) { sendResponse({ url: null }); return; }
// Filter by category if specified
if (msg.category) {
const stored = await chrome.storage.local.get('feedData');
const all = stored.feedData?.blogs?.entries || [];
const filtered = all.filter(e => e.categories && e.categories.includes(msg.category));
if (filtered.length === 0) { sendResponse({ url: null }); return; }
const pick = filtered[Math.floor(Math.random() * filtered.length)];
const url = unwrapSmallwebUrl(pick.url);
await setArticleInfo(sender.tab.id, url, pick.title, 'cat/' + msg.category);
await prepareIframe(url, sender.tab.id);
console.log('[Kagi NTP] source: cat/' + msg.category + ' | URL:', url);
sendResponse({ url, title: pick.title });
} else {
await setArticleInfo(sender.tab.id, entry.url, entry.title, 'feed/blogs');
await prepareIframe(entry.url, sender.tab.id);
console.log('[Kagi NTP] source: feed/blogs (no category) | URL:', entry.url);
sendResponse({ url: entry.url, title: entry.title });
}
} catch (e) {
sendResponse({ url: null });
}
})();
return true;
}
// Prepare iframe for custom URL
if (msg.action === 'prepareIframe' && sender.tab) {
prepareIframe(msg.url, sender.tab.id)
.then(() => sendResponse({ ready: true }))
.catch(() => sendResponse({ ready: false }));
return true;
}
// Popup reads article info
if (msg.action === 'getArticleInfo') {
const tabId = msg.tabId || sender.tab?.id;
getArticleInfo(tabId).then(info => sendResponse(info));
return true;
}
if (msg.action === 'getHistory') {
chrome.storage.local.get('articleHistory', (stored) => {
sendResponse(stored.articleHistory || []);
});
return true;
}
if (msg.action === 'clearHistory') {
chrome.storage.local.remove('articleHistory', () => sendResponse({ success: true }));
return true;
}
if (msg.action === 'bookmarkArticle') {
(async () => {
const folder = await getBookmarkFolder(msg.source);
await chrome.bookmarks.create({ parentId: folder.id, title: msg.title, url: msg.url });
sendResponse({ success: true });
})();
return true;
}
if (msg.action === 'appreciatePost') {
appreciatePost(msg.url).then(ok => sendResponse({ success: ok }));
return true;
}
if (msg.action === 'searchDefault' && sender.tab) {
chrome.search.query({ text: msg.query, tabId: sender.tab.id });
}
});
// ═══════════════════════════════════════
// BING/CORTANA → DEFAULT SEARCH ENGINE
// ═══════════════════════════════════════
const BING_REDIRECT_RULE_ID = 9999;
async function setBingRedirect(enabled) {
if (enabled) {
const extUrl = chrome.runtime.getURL('index.html');
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [BING_REDIRECT_RULE_ID],
addRules: [{
id: BING_REDIRECT_RULE_ID,
priority: 2,
action: {
type: 'redirect',
redirect: {
regexSubstitution: extUrl + '?q=\\1'
}
},
condition: {
regexFilter: '^https?://(?:www\\.)?bing\\.com/.*[?&]q=([^&]*)',
resourceTypes: ['main_frame']
}
}]
});
} else {
await chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: [BING_REDIRECT_RULE_ID]
});
}
}
// ═══════════════════════════════════════
// INIT & ICON
// ═══════════════════════════════════════
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.get(
['tabTakeoverEnabled', 'blockFocusEnabled', 'smallWebEnabled', 'selectedCategories', 'selectedFeeds', 'customUrl', 'bingRedirectEnabled'],
(result) => {
const defaults = {};
if (result.tabTakeoverEnabled === undefined) defaults.tabTakeoverEnabled = true;
if (result.blockFocusEnabled === undefined) defaults.blockFocusEnabled = true;
if (result.smallWebEnabled === undefined) defaults.smallWebEnabled = false;
if (result.selectedCategories === undefined) defaults.selectedCategories = ALL_CATEGORIES;
if (result.selectedFeeds === undefined) defaults.selectedFeeds = ALL_FEEDS;
if (result.customUrl === undefined) defaults.customUrl = '';
if (Object.keys(defaults).length > 0) chrome.storage.sync.set(defaults);
setBingRedirect(result.bingRedirectEnabled || false);
}
);
Object.keys(FEED_ENDPOINTS).forEach(name => getRandomFeedEntry(name));
});
chrome.runtime.onStartup.addListener(() => {
chrome.storage.sync.get(['selectedFeeds', 'bingRedirectEnabled'], (result) => {
if (result.selectedFeeds === undefined) {
chrome.storage.sync.set({ selectedFeeds: ALL_FEEDS });
}
setBingRedirect(result.bingRedirectEnabled || false);
});
Object.keys(FEED_ENDPOINTS).forEach(name => getRandomFeedEntry(name));
});
// Focus-blocking script for kagi.com (static rules.json handles headers)
chrome.storage.sync.get(['blockFocusEnabled'], (result) => {
if (result.blockFocusEnabled !== false) {
chrome.scripting.registerContentScripts([{
id: 'block-focus-kagi',
matches: ['https://kagi.com/*'],
js: ['block-focus.js'],
runAt: 'document_start',
world: 'MAIN',
allFrames: true
}]).catch(() => {}); // already registered
}
});
chrome.storage.onChanged.addListener((changes) => {
if (changes.tabTakeoverEnabled) {
updateIcon(changes.tabTakeoverEnabled.newValue !== false);
}
if (changes.bingRedirectEnabled) {
setBingRedirect(changes.bingRedirectEnabled.newValue || false);
}
if (changes.blockFocusEnabled) {
if (changes.blockFocusEnabled.newValue !== false) {
chrome.scripting.registerContentScripts([{
id: 'block-focus-kagi',
matches: ['https://kagi.com/*'],
js: ['block-focus.js'],
runAt: 'document_start',
world: 'MAIN',
allFrames: true
}]).catch(() => {});
} else {
chrome.scripting.unregisterContentScripts({ ids: ['block-focus-kagi'] }).catch(() => {});
}
}
});
async function updateIcon(enabled) {
if (enabled) {
chrome.action.setIcon({
path: { 16: 'icons/icon16.png', 48: 'icons/icon48.png', 128: 'icons/icon128.png' }
});
return;
}
const sizes = [16, 48, 128];
const imageData = {};
for (const size of sizes) {
const resp = await fetch('icons/icon' + size + '.png');
const blob = await resp.blob();
const bitmap = await createImageBitmap(blob);
const canvas = new OffscreenCanvas(size, size);
const ctx = canvas.getContext('2d');
ctx.drawImage(bitmap, 0, 0);
const data = ctx.getImageData(0, 0, size, size);
const px = data.data;
for (let i = 0; i < px.length; i += 4) {
const gray = Math.round(0.299 * px[i] + 0.587 * px[i + 1] + 0.114 * px[i + 2]);
px[i] = gray; px[i + 1] = gray; px[i + 2] = gray;
px[i + 3] = Math.round(px[i + 3] * 0.5);
}
imageData[size] = data;
}
chrome.action.setIcon({ imageData });
}
chrome.storage.sync.get(['tabTakeoverEnabled'], (result) => {
updateIcon(result.tabTakeoverEnabled !== false);
});