-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
118 lines (98 loc) · 3.13 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// ----- Options -----
browser.action.onClicked.addListener(handleClick);
function handleClick() {
browser.runtime.openOptionsPage();
}
// ----- Business Logic -----
const MENU_ITEM_ID = "translate-selection";
browser.contextMenus.create({
id: MENU_ITEM_ID,
title: "Translating..",
contexts: ["selection"]
});
browser.contextMenus.onShown.addListener(async (info, tab) => {
updateMenuItem("Translating..");
const displayedText = await translate(info.selectionText.trim());
updateMenuItem(displayedText);
});
browser.contextMenus.onClicked.addListener(async (info, tab) => {
const displayedText = await translate(info.selectionText);
replaceText(tab, displayedText);
});
async function translate(selectedText){
const l1 = (await browser.storage.local.get('language1')).language1 || 'English';
const l2 = (await browser.storage.local.get('language2')).language2 || 'German';
const lang1 = getAbbreviationForLanguage(l1);
const lang2 = getAbbreviationForLanguage(l2);
const translatedWord1 = await fetchTranslationBing(selectedText, lang1, lang2);
let displayedText = translatedWord1;
if (equalsIgnoringCase(selectedText, translatedWord1)) {
displayedText = await fetchTranslationBing(selectedText, lang2, lang1);
}
return displayedText;
}
async function replaceText(tab, replacementText){
try {
await browser.scripting.executeScript({
target: {
tabId: tab.id,
allFrames: true,
},
files: ["content-script.js"],
});
browser.tabs.sendMessage(tab.id, replacementText);
} catch (err) {
console.error(`failed to execute script: ${err}`);
}
}
function updateMenuItem(text) {
browser.contextMenus.update(MENU_ITEM_ID, {
title: text
});
browser.contextMenus.refresh();
}
function equalsIgnoringCase(text, other) {
return text.localeCompare(other, undefined, { sensitivity: 'base' }) === 0;
}
function getAbbreviationForLanguage(language) {
let abbrevation = 'en';
switch (language) {
case 'German':
abbrevation = 'de';
break;
case 'Italian':
abbrevation = 'it';
break;
case 'French':
abbrevation = 'fr';
break;
case 'Spanish':
abbrevation = 'es';
break;
case 'Chinese Simplified':
abbrevation = 'zh-Hans';
break;
}
return abbrevation;
}
async function fetchTranslationBing(wordToTranslate, languageFrom, languageTo) {
const headers = new Headers();
headers.append("Content-type", "application/json; charset=UTF-8");
headers.append("User-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0");
const body = `["${wordToTranslate}"]`;
const request = new Request(`https://edge.microsoft.com/translate/translatetext?from=${languageFrom}&to=${languageTo}`, {
method: "POST",
headers: headers,
body: body
});
try {
const response = await fetch(request);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const json = await response.json();
return json[0]?.translations[0]?.text;
} catch (error) {
console.error(error.message);
}
}