-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathmessage.js
51 lines (41 loc) · 1.07 KB
/
message.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
export const EVENTS = {
SEARCH_WORD: 'SEARCH_WORD',
OPEN_NEW_TAB: 'OPEN_NEW_TAB',
ADD_WORD_SHANBAY: 'ADD_WORD_SHANBAY',
CLEAR_SHANBAY_TOKEN: 'CLEAR_SHANBAY_TOKEN',
}
// event page receives an event
export function onMessage(eventName, handler) {
chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
const { eventName: e, data } = req
if (e !== eventName) {
return false
}
handler(data, sendResponse)
return true
})
}
// send message to event page
export function sendMessage(eventName, data) {
return new Promise((resolve) => {
chrome.runtime.sendMessage({
eventName,
data,
}, (res) => {
resolve(res)
})
})
}
export function openLink(word) {
sendMessage(EVENTS.OPEN_NEW_TAB, word)
}
export async function searchWord(word) {
const res = await sendMessage(EVENTS.SEARCH_WORD, word)
return res
}
export async function addNotebookWord(word) {
return sendMessage(EVENTS.ADD_WORD_SHANBAY, word)
}
export async function clearShanbayToken() {
return sendMessage(EVENTS.CLEAR_SHANBAY_TOKEN)
}