-
Notifications
You must be signed in to change notification settings - Fork 3
/
background.js
35 lines (32 loc) · 1.08 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
window.chrome.runtime.onInstalled.addListener(() => {
window.chrome.contextMenus.removeAll(() => {
window.chrome.contextMenus.create({
id: 'sdf9876yhjuy6',
title: 'Add to word list',
contexts: ['selection'],
});
});
});
function addWord(newWord) {
newWord = newWord.trim();
if (!newWord) return;
window.chrome.storage.sync.get(['words'], (result) => {
const { words = '[]' } = result;
const parsedWords = JSON.parse(words);
if (parsedWords.find(w => w === newWord)) {
return;
}
window.chrome.storage.sync.set({
words: JSON.stringify([...parsedWords, newWord]),
}, () => {
window.chrome.runtime.sendMessage({ method: 'listWords' });
window.chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
window.chrome.tabs.sendMessage(tabs[0].id, { method: 'remove' });
});
});
});
}
window.chrome.runtime.onMessage.addListener(({ method, text }) => {
if (method === 'addWord') addWord(text);
});
window.chrome.contextMenus.onClicked.addListener(({ selectionText }) => addWord(selectionText));