-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoffscreen.js
More file actions
50 lines (44 loc) · 1.87 KB
/
offscreen.js
File metadata and controls
50 lines (44 loc) · 1.87 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
import { runTranslatorOnHtml } from './sources/translatorRunner.js';
console.debug('[offscreen] started');
// Provide a minimal compatibility shim: if `browser` is missing, alias it to `chrome`.
if (typeof browser === "undefined" && typeof chrome !== "undefined") {
globalThis.browser = chrome;
}
browser.runtime.onMessage.addListener(async (msg, sender, sendResponse) => {
if (!msg || msg.type !== 'runTranslator') return;
const { url, translatorPath, translators } = msg;
try {
const resp = await fetch(url, { credentials: 'omit' });
const html = await resp.text();
const list = Array.isArray(translators) && translators.length ? translators : (translatorPath ? [translatorPath] : []);
if (!list.length) throw new Error('No translator paths provided');
let lastError = null;
for (const t of list) {
try {
const translatorUrl = browser.runtime.getURL(t);
const mod = await import(translatorUrl);
const result = await runTranslatorOnHtml(mod, html, url);
if (result !== null && typeof result !== 'undefined') {
await browser.runtime.sendMessage({ type: 'offscreenResult', url, result });
sendResponse({ ok: true });
return true;
}
} catch (e) {
lastError = e;
console.warn('[offscreen] translator failed, trying next:', t, e);
continue;
}
}
if (lastError) {
await browser.runtime.sendMessage({ type: 'offscreenResult', url, error: String(lastError) });
sendResponse({ ok: false, error: String(lastError) });
} else {
await browser.runtime.sendMessage({ type: 'offscreenResult', url, result: null });
sendResponse({ ok: true, result: null });
}
} catch (e) {
await browser.runtime.sendMessage({ type: 'offscreenResult', url, error: String(e) });
sendResponse({ ok: false, error: String(e) });
}
return true;
});