forked from cheeaun/max-tabs
-
Notifications
You must be signed in to change notification settings - Fork 10
/
background.js
106 lines (93 loc) · 2.67 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
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
/*global browser, chroma */
let title = browser.i18n.getMessage('title');
let maxTabs = 10;
let includePinned = false;
let colorScale = chroma.scale(['#A6A6A6', '#B90000']);
function updatePrefs() {
return new Promise((resolve, reject) => {
browser.storage.sync.get({
"maxTabs": 10,
"includePinned": false
}, items => {
maxTabs = items.maxTabs;
includePinned = items.includePinned;
resolve();
});
});
}
function updateButton(numTabs) {
browser.browserAction.setTitle({
title: title + ' - ' + numTabs + '/' + maxTabs
});
browser.browserAction.setBadgeText({
text: numTabs > 99 ? '99+' : numTabs.toString()
});
browser.browserAction.setBadgeBackgroundColor({
color: colorScale(numTabs/maxTabs).hex()
});
}
async function queryNumTabs() {
let tabs = await browser.tabs.query({
currentWindow: true,
pinned: includePinned ? null : false
});
return tabs.length;
}
browser.tabs.onCreated.addListener(tab => {
if (browser.windows.get(tab.windowId).focused) {
// We only care about the current window
return;
}
if (tab.id != browser.tabs.TAB_ID_NONE) {
queryNumTabs().then(numTabs => {
if (numTabs > maxTabs) {
browser.tabs.remove(tab.id).then(() => {
browser.notifications.create("", {
type: "basic",
title: title,
message: browser.i18n.getMessage('notOpenMaxTabs', maxTabs)
});
});
} else {
updateButton(numTabs);
}
});
}
});
browser.tabs.onRemoved.addListener((tabId, removeInfo) => {
if (removeInfo.isWindowClosing) {
return;
}
queryNumTabs().then(updateButton);
});
browser.tabs.onDetached.addListener((tabId, detachInfo) => {
if (browser.windows.get(detachInfo.oldWindowId).focused) {
queryNumTabs().then(updateButton);
}
});
browser.tabs.onAttached.addListener((tabId, attachInfo) => {
if (browser.windows.get(attachInfo.oldWindowId).focused) {
queryNumTabs().then(updateButton);
}
});
const filter = {
properties: ["pinned"]
}
browser.tabs.onUpdated.addListener((tabId, changeInfo, tabInfo) => {
queryNumTabs().then(updateButton);
}, filter);
browser.windows.onFocusChanged.addListener(windowId => {
queryNumTabs().then(updateButton);
});
browser.storage.onChanged.addListener((changes, areaName) => {
updatePrefs().then(() => {
queryNumTabs().then(updateButton);
});
});
browser.browserAction.disable();
updatePrefs().then(() => {
queryNumTabs().then(updateButton);
});