-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbackground.js
71 lines (58 loc) · 1.5 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
'use strict';
const kTST_ID = '[email protected]';
async function registerToTST() {
try {
const self = await browser.management.getSelf();
let success = await browser.runtime.sendMessage(kTST_ID, {
type: 'register-self',
name: self.id,
});
return success;
} catch (e) {
// TST is not available
}
}
browser.runtime.onMessageExternal.addListener((aMessage, aSender) => {
switch (aSender.id) {
case kTST_ID:
switch (aMessage.type) {
case 'ready':
registerToTST();
break;
}
break;
}
});
registerToTST().then(res => {
browser.tabs.onActivated.addListener(callback);
browser.tabs.onCreated.addListener(callback);
browser.tabs.onRemoved.addListener(callback);
});
async function getSortedWinTabs() {
const tabs = await browser.tabs.query({ currentWindow: true });
tabs.sort((a, b) => (a.lastAccessed < b.lastAccessed ? 1 : -1));
return tabs;
}
async function wait(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function callback() {
await wait(300);
const sortedTabs = await getSortedWinTabs();
const allTabsIDs = sortedTabs.reduce((allIDs, currentTab) => {
allIDs.push(currentTab.id);
return allIDs;
}, []);
browser.runtime.sendMessage(kTST_ID, {
type: 'remove-tab-state',
tabs: allTabsIDs,
state: 'last-active',
});
browser.runtime.sendMessage(kTST_ID, {
type: 'add-tab-state',
tabs: [sortedTabs[1].id],
state: 'last-active',
});
}