-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
98 lines (82 loc) · 2.25 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
"use strict";
const TST_ID = "[email protected]";
const DEFAULT_SETTINGS = {
// Delay in ms before switching to hovered tab
"switching-delay": 100,
};
// The current settings
let settings;
// Load settings, setup listeners and register to TST
(async () => {
settings = await browser.storage.local.get(DEFAULT_SETTINGS);
await browser.storage.local.set(settings); // Save any missing defaults
browser.storage.onChanged.addListener(handleSettingsChange);
browser.runtime.onMessageExternal.addListener(handleTSTMessage);
// Register directly in case we are activated after TST
await registerToTST();
})();
async function handleSettingsChange(changes) {
for(let key in changes) {
let change = changes[key];
if(change.newValue !== undefined) {
settings[key] = change.newValue;
}
}
}
async function registerToTST() {
try {
const self = await browser.management.getSelf();
await browser.runtime.sendMessage(TST_ID, {
type: "register-self",
name: self.id,
listeningTypes: ["ready", "tab-mouseover", "tab-mouseout"]
});
} catch(e) {
// Could not register
console.log("Could not register to TST")
return false;
}
return true;
}
async function activateTab(tab) {
try {
await browser.runtime.sendMessage(TST_ID, {
type: "focus",
tab: tab
});
} catch(e) {
// Happens when the tab is closed during the timeout
}
}
let timer = null;
function startTimer(tab) {
let callback = async () => {
timer = null;
await activateTab(tab);
};
timer = setTimeout(callback, settings["switching-delay"]);
}
function stopTimer() {
if(timer !== null) {
clearTimeout(timer);
timer = null;
}
}
async function handleTSTMessage(message, sender) {
if(sender.id !== TST_ID) {
return;
}
switch (message.type) {
case "ready":
registerToTST();
break;
case "tab-mouseover":
stopTimer();
let tab = message.tab;
startTimer(tab.id);
break;
case "tab-mouseout":
stopTimer();
break;
}
}