-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
61 lines (58 loc) · 1.63 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
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
"id": "translationContextMenu",
"title": "translateThenSearch",
"contexts": ["selection"]
});
});
chrome.contextMenus.onClicked.addListener(function (clickData) {
if (clickData.menuItemId == 'translationContextMenu') {
console.log(clickData);
text = clickData.selectionText;
translateThenSearch(text);
}
});
function translateThenSearch(input) {
fetch("http://124.220.81.24:8080/to-en?text=" input, {
method: "GET", // or 'PUT'
headers: {
"Content-Type": "application/json"
}
})
.then((response) => response.json())
.then(function (response) {
console.info('fetch()', response);
chrome.tabs.query({
"active": true,
"currentWindow": true
},
function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
"functiontoInvoke": "translateThenSearch",
"en": response[0].translations[0].text
});
}
);
})
.catch((error) => {
console.error("Error:", error);
});
}
chrome.commands.onCommand.addListener(async (command) => {
console.log(`Command "${command}" triggered`);
if (command == "translate-then-search") {
chrome.tabs.query({
"active": true,
"currentWindow": true
},
async function (tabs) {
const response = await chrome.tabs.sendMessage(tabs[0].id, {
"functiontoInvoke": "getSearchInputValue",
});
console.log(response);
var searchInputValue = response.searchInputValue;
translateThenSearch(searchInputValue);
}
);
}
});