-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
67 lines (59 loc) · 2.22 KB
/
background.js
File metadata and controls
67 lines (59 loc) · 2.22 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
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "translate-sidepanel",
title: "Translate '%s' in Side Panel",
contexts: ["selection"],
});
chrome.contextMenus.create({
id: "read-aloud",
title: "Listen to '%s'",
contexts: ["selection"],
});
});
function requestTranslation(text, tab) {
const newQuery = {
text: text,
ts: Date.now()
};
chrome.storage.local.set({ lastQuery: newQuery }, () => {
chrome.sidePanel.open({ windowId: tab.windowId });
});
}
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "translate-sidepanel") {
requestTranslation(info.selectionText, tab);
} else if (info.menuItemId === "read-aloud") {
chrome.tts.stop();
chrome.tts.speak(info.selectionText, { rate: 0.9 });
}
});
chrome.commands.onCommand.addListener((command) => {
if (command === "translate-shortcut") {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (!tabs[0]) return;
const tab = tabs[0];
chrome.sidePanel.open({ windowId: tab.windowId }).then(() => {
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: () => window.getSelection().toString()
}).then((results) => {
const text = results[0]?.result?.trim();
if (text) {
chrome.storage.local.set({ lastQuery: { text: text, ts: Date.now() } });
}
}).catch(err => {
});
});
});
}
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'translateWord') {
const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${request.lang}&dt=t&q=${encodeURIComponent(request.text)}`;
fetch(url)
.then(res => res.json())
.then(data => sendResponse(data[0][0][0]))
.catch(() => sendResponse("Translation error"));
return true;
}
});