-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackground.js
89 lines (80 loc) · 2.73 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
chrome.contextMenus.onClicked.addListener(onClickContextMenuOptions);
chrome.runtime.onInstalled.addListener(createContextMenuOptions);
function createContextMenuOptions() {
chrome.contextMenus.create({
"title": "Çevir",
"id": "translate",
"contexts": [
"selection"
]
});
}
function doInCurrentTab(callback) {
chrome.tabs.query(
{ active: true, lastFocusedWindow: true },
([tab]) => {
callback([tab][0]);
}
);
}
function onClickContextMenuOptions(info, tab) {
if (info.menuItemId === "translate") {
const selectedText = info.selectionText;
searchSelectedText(selectedText, tab);
}
}
chrome.commands.onCommand.addListener(function (command) {
if (command === "search-phrase") {
doInCurrentTab(function (tab) {
chrome.scripting.executeScript({
target: { tabId: tab.id, allFrames: true },
files: ['selected-text-getter.js'],
}).then((selectedTextPerFrame) => {
if ((selectedTextPerFrame.length > 0) && selectedTextPerFrame[0].result && (typeof (selectedTextPerFrame[0].result) === 'string')) {
const selectedText = selectedTextPerFrame[0].result;
searchSelectedText(selectedText, tab);
}
});
});
}
});
function searchSelectedText(selectedText, tab) {
console.log("Selected text:" + selectedText);
chrome.scripting.executeScript({
target: { tabId: tab.id, allFrames: true },
files: ['balloon.js'],
}).then(() => search(selectedText, tab.id));
}
async function search(searchString, tabId) {
if (!searchString) {
return;
}
const response = await chrome.tabs.sendMessage(tabId, { method: 'createBalloon' });
console.log(response);
fetch(getSearchURL(searchString))
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(async responseText => {
const response = await chrome.tabs.sendMessage(tabId, {
method: 'showResult',
searchURL: getSearchURL(searchString),
rawResponseText: responseText,
externalRequestSucceeded: true
});
console.log(response);
})
.catch(async error => {
const response = await chrome.tabs.sendMessage(tabId, {
method: 'showResult',
externalRequestSucceeded: false
});
console.log(response);
});
}
function getSearchURL(searchString) {
return "http://tureng.com/search/" + searchString;
}