-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
52 lines (44 loc) · 1.47 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
async function translate(src, dst, content) {
const apiKey = (await chrome.storage.local.get("api-key"))["api-key"];
const response = await fetch("https://api.xl8.ai/v1/trans/request/rt", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
source_language: src,
target_language: dst,
sentences: [content],
}),
});
if (!response.ok) {
throw new Error(`${response.statusText}: ${await response.json()}`);
}
const data = await response.json();
return data["sentences"][0];
}
const contextMenuId = "xl8translate";
chrome.contextMenus.create({
id: contextMenuId,
contexts: ["selection"],
title: "Translate with XL8",
});
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId === contextMenuId && info.selectionText) {
if (tab && tab.id) {
const translated = await translate("en", "ko", info.selectionText);
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: (translated) => {
window.dispatchEvent(
new CustomEvent("xl8translated", {
detail: translated,
})
);
},
args: [translated],
});
}
}
});