forked from leezu/zhongwen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
110 lines (96 loc) · 3.74 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
/*
Zhongwen - A Chinese-English Popup Dictionary
Original work Copyright (C) 2012 Christian Schiller
Modified work Copyright (C) 2017 Leonard Lausen
https://chrome.google.com/extensions/detail/kkmlkkjojmombglmlpbpapmhcaljjkde
*/
browser.runtime.onMessage.addListener(function(request, sender, response) {
switch(request.type) {
case 'search':
var e = zhongwenMain.search(request.text);
return Promise.resolve(e);
case 'open':
var tabID = zhongwenMain.tabIDs[request.tabType];
if (tabID) {
chrome.tabs.get(tabID, function(tab) {
if (tab && (tab.url.substr(-13) == 'wordlist.html')) {
chrome.tabs.reload(tabID);
chrome.tabs.update(tabID, {
active: true
});
} else {
chrome.tabs.create({
url: request.url
}, function(tab) {
zhongwenMain.tabIDs[request.tabType] = tab.id;
if (request.tabType == 'wordlist') {
// make sure the table is sized correctly
chrome.tabs.reload(tab.id);
}
});
}
});
} else {
chrome.tabs.create({
url: request.url
}, function(tab) {
zhongwenMain.tabIDs[request.tabType] = tab.id;
if (request.tabType == 'wordlist') {
// make sure the table is sized correctly
chrome.tabs.reload(tab.id);
}
});
}
break;
case 'add':
var json = localStorage['wordlist'];
var wordlist;
if (json) {
wordlist = JSON.parse(json);
} else {
wordlist = [];
}
for (var i in request.entries) {
var entry = {};
entry.simplified = request.entries[i].simplified;
entry.traditional = request.entries[i].traditional;
entry.pinyin = request.entries[i].pinyin;
entry.definition = request.entries[i].definition;
wordlist.push(entry);
}
localStorage['wordlist'] = JSON.stringify(wordlist);
tabID = zhongwenMain.tabIDs['wordlist'];
if (tabID) {
chrome.tabs.get(tabID, function(tab) {
if (tab) {
chrome.tabs.reload(tabID);
}
});
}
break;
default:
// ignore
}
});
browser.browserAction.onClicked.addListener(zhongwenMain.enableToggle)
browser.tabs.onActivated.addListener(zhongwenMain.onTabActivated)
browser.tabs.onUpdated.addListener(zhongwenMain.onTabUpdated)
let enabledPromise = browser.storage.local.get({enabled: 0})
Promise.all([enabledPromise]).then(([storage]) => {
var tab // Can't retrieve tab object in background script
if (storage.enabled === 1) {
zhongwenMain.enable(tab)
browser.browserAction.setBadgeBackgroundColor({
'color': [255, 0, 0, 255]
})
browser.browserAction.setBadgeText({
'text': 'On'
})
}
})
browser.contextMenus.create({
title: 'Open word list',
id: 'wordlist-browser_action',
onclick: zhongwenMain.wordlistTab,
contexts: ['browser_action']
})