This repository has been archived by the owner on Jun 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
content-script.js
52 lines (47 loc) · 1.66 KB
/
content-script.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
let word;
let cachedWords;
// In case of ugly text selections
function addSlashes( str ) {
return str.slice().replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
document.addEventListener('click', event => {
// TODO: Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index.
const range = window.getSelection().getRangeAt(0);
const selectedNode = range.cloneContents();
if (selectedNode.textContent && selectedNode.textContent.length) {
[word] = selectedNode.textContent.split(' ');
word = addSlashes(word);
} else {
word = null;
}
chrome.runtime.sendMessage({
word,
x:
event.clientX +
(document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft),
y:
event.clientY +
(document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop),
});
});
// Listening messages from extention (popup) or background
chrome.extension.onMessage.addListener((request, sender, sendResponse) => {
if (request.method) {
if (request.method === 'wordly-get') {
chrome.storage.sync.get({ wordly: [] }, stores => {
cachedWords = stores.wordly;
sendResponse({ wordly: stores.wordly });
});
} else if (request.method === 'wordly-remove') {
const wordToRemove = request.word;
if (!wordToRemove) {
return true;
}
// Can improve the efficiency of this if words are stored in a hash structure
const index = cachedWords.findIndex(obj => obj.word === wordToRemove);
cachedWords.splice(index, 1);
chrome.storage.sync.set({ wordly: cachedWords });
}
}
return true;
});