-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
74 lines (62 loc) · 1.86 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
var tabsInWindow = {};
var tabsInAllWindows = 0;
function updateTabsInWindow(winId, n) {
tabsInWindow[winId] = n;
}
function updateTabsInAllWindows(tabs) {
tabsInAllWindows = tabs.length;
}
function updateBadge(winId) {
// winId is -1 if no Firefox window has focus at all
if (winId >= 0) {
browser.browserAction.setBadgeText({text: String(tabsInWindow[winId])});
}
}
function messageHandler(request, sender, sendResponse) {
curr = browser.windows.getCurrent();
curr.then(function(win) {
sendResponse({currentWindow: tabsInWindow[win.id], allWindows: tabsInAllWindows})
});
// This is necessary to be able to send the response back asynchronously
return true;
}
function initCounters() {
current = browser.windows.getCurrent();
current.then(function(curr) {
all = browser.windows.getAll()
all.then(function(wins) {
wins.forEach(function(win) {
tabs = browser.tabs.query({windowId: win.id});
tabs.then(function(tabs) {
updateTabsInWindow(win.id, tabs.length);
if (win.id == curr.id) {
updateBadge(win.id)
}
});
});
});
});
browser.tabs.query({}, updateTabsInAllWindows);
}
function increaseCounters(tab) {
tabsInWindow[tab.windowId] += 1;
updateBadge(tab.windowId);
tabsInAllWindows += 1;
}
function decreaseCounters(tabId, removeInfo) {
if (!removeInfo.isWindowClosing) {
tabsInWindow[removeInfo.windowId] -= 1;
updateBadge(removeInfo.windowId);
}
tabsInAllWindows -= 1;
}
function createWindow(win) {
updateTabsInWindow(win.id, 1);
updateBadge(win.id);
}
initCounters();
browser.runtime.onMessage.addListener(messageHandler);
browser.tabs.onCreated.addListener(increaseCounters);
browser.tabs.onRemoved.addListener(decreaseCounters);
browser.windows.onFocusChanged.addListener(updateBadge);
browser.windows.onCreated.addListener(createWindow);