-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbackground.js
111 lines (103 loc) · 2.69 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
107
108
109
110
111
let tabsCache = {}
let activeTabId = -1
// tab created
browser.tabs.onCreated.addListener(tab => {
tabsCache[tab.id] = tab.title
nativePort.postMessage({
tabs: tabsCache
})
})
// tab removed
browser.tabs.onRemoved.addListener(tabId => {
delete tabsCache[tabId]
nativePort.postMessage({
tabs: tabsCache
})
})
// tab updated
browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if ('title' in changeInfo) {
tabsCache[tabId] = changeInfo.title
nativePort.postMessage({
tabs: tabsCache
})
}
browser.sessions.getTabValue(tabId, 'customTitle').then(customTitle => {
if (customTitle) {
// apply custom title
browser.tabs.executeScript(tabId, {
code: `document.title = '${customTitle}'`
})
} else {
// custom title doesn't exist
browser.sessions.removeTabValue(tabId, 'oldTitle')
}
})
})
// tab activated
browser.tabs.onActivated.addListener((activeInfo) => {
activeTabId = activeInfo.tabId
nativePort.postMessage({
activeTabId: activeTabId
})
})
// activate/focus tab
function activate(tabId) {
browser.tabs.update(tabId, {active: true}, tab => {
browser.windows.update(tab.windowId, {focused: true})
})
}
// rename tab
function rename(tabId, newTitle) {
if (newTitle == '') {
// restore old title
browser.sessions.removeTabValue(tabId, 'customTitle')
browser.sessions.getTabValue(tabId, 'oldTitle').then(oldTitle => {
if (oldTitle) {
// apply old title
browser.tabs.executeScript(tabId, {
code: `document.title = '${oldTitle}'`
})
browser.sessions.removeTabValue(tabId, 'oldTitle')
}
})
} else {
// save old title and apply new title
browser.tabs.get(tabId).then(tabInfo => {
browser.sessions.getTabValue(tabId, 'oldTitle').then(oldTitle => {
if (!oldTitle) {
browser.sessions.setTabValue(tabId, 'oldTitle', tabInfo.title)
}
})
browser.sessions.setTabValue(tabId, 'customTitle', newTitle)
browser.tabs.executeScript(tabId, {
code: `document.title = '${newTitle}'`
})
})
}
}
// native interface
let nativePort = browser.runtime.connectNative('dbus_tabs')
nativePort.onMessage.addListener(message => {
switch(message.action) {
case 'activate':
activate(parseInt(message.tabId))
break
case 'rename':
rename(parseInt(message.tabId), message.newTitle)
break
}
})
// initialize tabs cache
browser.tabs.query({}).then(tabs => {
for (let tab of tabs) {
tabsCache[tab.id] = tab.title
}
nativePort.postMessage({
tabs: tabsCache
})
})
activeTabId = browser.tabs.getCurrent().tabId
nativePort.postMessage({
activeTabId: activeTabId
})