-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
71 lines (60 loc) · 1.71 KB
/
background.js
File metadata and controls
71 lines (60 loc) · 1.71 KB
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
var previousLookup = "";
function replaceSelectedText(info, tab) {
let newText = info.menuItemId;
chrome.tabs.query({ currentWindow: true, active: true }, function (activeTabs) {
chrome.tabs.sendMessage(
activeTabs[0].id,
{ message: "textfunk_replace_word", data: newText },
function (response) { });
});
}
// Add the synonym choices to sub menu
function addChoices(words) {
var menu = chrome.contextMenus.create(
{
title: "Synonym(s) for '%s'",
contexts: ["selection"]
});
if (!words) {
return;
}
words.forEach(function (word) {
chrome.contextMenus.create(
{
title: word.word,
parentId: menu,
id: word.word,
onclick: replaceSelectedText,
contexts: ["selection"]
});
});
}
function requestSynonyms(word) {
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.datamuse.com/words?rel_syn=" + word, true);
xhr.onload = function () {
if (this.readyState === 4) {
if (this.status === 200) {
console.log(this.responseText);
let wordList = JSON.parse(this.responseText);
addChoices(wordList);
} else {
console.error(this.statusText);
}
}
}
xhr.send();
}
// Catch message from content script
function onMessage(request, sender, sendResponse) {
if (request.message !== "textfunk_word_selected" || request.data === previousLookup)
return;
// Reset the menu
chrome.contextMenus.removeAll();
let trimmed = request.data.trim();
let lower = trimmed.toLowerCase();
requestSynonyms(lower);
// Save results in case user opens context menu for same word again
previousLookup = lower;
}
chrome.runtime.onMessage.addListener(onMessage);