-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
75 lines (62 loc) · 2.58 KB
/
background.js
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
const DEFAULT_TAB_LIMIT = 10;
const DEFAULT_ARCHIVE_TAB_LIMIT = 50;
let tabMax;
let archiveTabMax;
let deletedTabs = [];
function updateBadge() {
const badgeValue = deletedTabs.length === 0 ? '' : String(deletedTabs.length);
chrome.action.setBadgeText({ text: badgeValue });
}
async function updateTabs({ newTab, unpinnedTabId } = {}) {
const tabs = await chrome.tabs.query({ pinned: false, currentWindow: true });
const numTabsToRemove = tabs.length - tabMax;
if (numTabsToRemove > 0) {
if (unpinnedTabId) {
// swap first and second tab locations so that newly unpinned tab isn't immediately removed
[tabs[0], tabs[1]] = [tabs[1], tabs[0]];
}
const tabsToRemove = tabs.filter((tab, index) => index < numTabsToRemove);
const tabIdsToRemove = tabsToRemove.map(tab => tab.id);
await chrome.tabs.remove(tabIdsToRemove);
// remove duplicate archived tabs
deletedTabs = deletedTabs.filter(deletedTab => (deletedTab.url !== newTab?.pendingUrl || deletedTab.title === newTab?.title) && !tabsToRemove.find(tab => deletedTab.url === tab.url && deletedTab.title === tab.title));
// add newly removed tabs to top of the archived tabs list
deletedTabs.unshift(...tabsToRemove.filter(tab => !tab.url?.startsWith('chrome://newtab/')));
if (deletedTabs.length > archiveTabMax) {
deletedTabs = deletedTabs.slice(0, archiveTabMax);
}
await chrome.storage.local.set({ deletedTabs });
}
updateBadge();
}
function initEventHandlers() {
chrome.storage.sync.get(['tabLimit', 'archivedTabLimit'], ({ tabLimit, archivedTabLimit }) => {
tabMax = tabLimit || DEFAULT_TAB_LIMIT;
archiveTabMax = archivedTabLimit || DEFAULT_ARCHIVE_TAB_LIMIT;
if (!tabLimit || !archivedTabLimit) {
chrome.storage.sync.set({ tabLimit: tabMax, archivedTabLimit: archiveTabMax });
}
});
chrome.tabs.onCreated.addListener(async (newTab) => {
updateTabs({ newTab });
});
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo) => {
if (changeInfo.pinned === false) {
updateTabs({ unpinnedTabId: tabId });
}
});
chrome.storage.onChanged.addListener(async ({ tabLimit, archivedTabLimit, deletedTabs: deleteTabsLocal = [] }) => {
tabMax = tabLimit?.newValue || tabMax;
archiveTabMax = archivedTabLimit?.newValue || archiveTabMax;
deletedTabs = deleteTabsLocal?.newValue || deletedTabs;
if (tabLimit?.newValue) {
updateTabs();
}
});
chrome.storage.local.get('deletedTabs', ({ deletedTabs: deletedTabsLocal = [] }) => {
deletedTabs = deletedTabsLocal;
updateBadge();
});
}
initEventHandlers();
updateTabs();