forked from koen92/tab_cycle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
72 lines (64 loc) · 1.54 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
let enabled = 0;
let tabsIds = []
let curTabIdx = 0
/*
* Updates the icon if tab cycling is enabled
*/
function updateIcon() {
browser.browserAction.setIcon({
path: enabled !== 0 ? {
30: "icons/cycle-enabled.png",
} : {
30: "icons/cycle-disabled.png",
},
});
}
function shuffle(a) {
console.log("Shuffling", a.length, "tabs")
let curr = a.length, rand
while (0 !== curr) {
rand = Math.floor(Math.random() * curr)
curr--
[a[curr], a[rand]] = [a[rand], a[curr]]
}
}
/*
* Make the next tab active
*/
function openNextTab() {
browser.tabs.query({currentWindow: true})
.then(tabs => {
if (tabsIds.length !== tabs.length) {
tabsIds = Array.from(tabs, t => t.id)
shuffle(tabsIds)
curTabIdx = -1
}
curTabIdx = (curTabIdx + 1) % tabsIds.length
const newId = tabsIds[curTabIdx];
console.log("New tab ===>", curTabIdx, newId)
if (curTabIdx === tabsIds.length - 1) {
shuffle(tabsIds)
}
return browser.tabs.update( newId, {active: true });
});
}
/*
* Enable periodic tab cycling
*/
function toggleTabCycle() {
if (enabled === 0) {
browser.storage.sync.get('delay')
.then((res) => {
const delay = (res.delay !== undefined) ? res.delay * 1000 : 5000;
enabled = setInterval(openNextTab, delay);
updateIcon();
});
} else {
clearInterval(enabled);
enabled = 0;
tabsIds = []
curTabIdx = 0
updateIcon();
}
}
browser.browserAction.onClicked.addListener(toggleTabCycle);