fix: change runtime.onMessage to async fn

This commit is contained in:
Gabe Yuan
2024-03-19 17:28:07 +08:00
parent 54a6189b0c
commit 1d9e9c1b7d
5 changed files with 57 additions and 109 deletions

View File

@@ -115,91 +115,42 @@ browser.runtime.onStartup.addListener(async () => {
/**
* 监听消息
*/
browser.runtime.onMessage.addListener(
({ action, args }, sender, sendResponse) => {
browser.runtime.onMessage.addListener(async ({ action, args }) => {
switch (action) {
case MSG_FETCH:
const { input, opts } = args;
fetchData(input, opts)
.then((data) => {
sendResponse({ data });
})
.catch((error) => {
sendResponse({ error: error.message, cause: error.cause });
});
break;
return await fetchData(input, opts);
case MSG_FETCH_LIMIT:
const { interval, limit } = args;
fetchPool.update(interval, limit);
sendResponse({ data: "ok" });
break;
return fetchPool.update(interval, limit);
case MSG_FETCH_CLEAR:
fetchPool.clear();
sendResponse({ data: "ok" });
break;
return fetchPool.clear();
case MSG_OPEN_OPTIONS:
browser.runtime.openOptionsPage();
sendResponse({ data: "ok" });
break;
return await browser.runtime.openOptionsPage();
case MSG_SAVE_RULE:
saveRule(args);
sendResponse({ data: "ok" });
break;
return await saveRule(args);
case MSG_INJECT_JS:
getCurTabId()
.then((tabId) =>
browser.scripting.executeScript({
target: { tabId: tabId, allFrames: true },
return await browser.scripting.executeScript({
target: { tabId: await getCurTabId(), allFrames: true },
func: injectInlineJs,
args: [args],
world: "MAIN",
})
)
.then(() => {
sendResponse({ data: "ok" });
})
.catch((error) => {
sendResponse({ error: error.message });
});
break;
case MSG_INJECT_CSS:
getCurTabId()
.then((tabId) =>
browser.scripting.executeScript({
target: { tabId: tabId, allFrames: true },
return await browser.scripting.executeScript({
target: { tabId: await getCurTabId(), allFrames: true },
func: injectInternalCss,
args: [args],
world: "MAIN",
})
)
.then(() => {
sendResponse({ data: "ok" });
})
.catch((error) => {
sendResponse({ error: error.message });
});
break;
case MSG_CONTEXT_MENUS:
const { contextMenuType } = args;
addContextMenus(contextMenuType);
sendResponse({ data: "ok" });
break;
return await addContextMenus(args.contextMenuType);
case MSG_COMMAND_SHORTCUTS:
browser.commands
.getAll()
.then((commands) => {
sendResponse({ data: commands });
})
.catch((error) => {
sendResponse({ error: error.message });
});
break;
return await browser.commands.getAll();
default:
sendResponse({ error: `message action is unavailable: ${action}` });
throw new Error(`message action is unavailable: ${action}`);
}
return true;
}
);
});
/**
* 监听快捷键

View File

@@ -138,13 +138,14 @@ export const fetchData = async (
}
if (!res?.ok) {
const cause = {
const msg = {
url: input,
status: res.status,
};
if (res.headers.get("Content-Type")?.includes("json")) {
cause.body = await res.json();
msg.response = await res.json();
}
throw new Error(`response: [${res.status}] ${res.statusText}`, { cause });
throw new Error(JSON.stringify(msg));
}
// 插入缓存
@@ -178,11 +179,7 @@ export const fetchPolyfill = async (input, opts) => {
// 插件
if (isExt && !isBg()) {
const res = await sendBgMsg(MSG_FETCH, { input, opts });
if (res.error) {
throw new Error(res.error, { cause: res.cause });
}
return res.data;
return await sendBgMsg(MSG_FETCH, { input, opts });
}
// 油猴/网页/BackgroundPage
@@ -196,10 +193,7 @@ export const fetchPolyfill = async (input, opts) => {
*/
export const updateFetchPool = async (interval, limit) => {
if (isExt) {
const res = await sendBgMsg(MSG_FETCH_LIMIT, { interval, limit });
if (res.error) {
throw new Error(res.error);
}
await sendBgMsg(MSG_FETCH_LIMIT, { interval, limit });
} else {
fetchPool.update(interval, limit);
}
@@ -210,10 +204,7 @@ export const updateFetchPool = async (interval, limit) => {
*/
export const clearFetchPool = async () => {
if (isExt) {
const res = await sendBgMsg(MSG_FETCH_CLEAR);
if (res.error) {
throw new Error(res.error);
}
await sendBgMsg(MSG_FETCH_CLEAR);
} else {
fetchPool.clear();
}

View File

@@ -2,7 +2,7 @@ import { loadingSvg } from "../../libs/svg";
export default function LoadingIcon() {
return (
<div
<span
style={{
display: "inline-block",
width: "1.2em",

View File

@@ -50,16 +50,22 @@ function TestButton({ translator, api }) {
alert.success(i18n("test_success"));
} catch (err) {
// alert.error(`${i18n("test_failed")}: ${err.message}`);
let msg = err.message;
try {
msg = JSON.stringify(JSON.parse(err.message), null, 2);
} catch (err) {
// skip
}
alert.error(
<>
<div>{`${i18n("test_failed")}: ${err.message}`}</div>
<div>{i18n("test_failed")}</div>
<pre
style={{
maxWidth: 400,
overflow: "auto",
}}
>
{JSON.stringify(err.cause || {}, null, 2)}
{msg}
</pre>
</>
);
@@ -124,7 +130,9 @@ function ApiFields({ translator }) {
onChange={handleChange}
multiline={mulkeysTranslators.includes(translator)}
helperText={
mulkeysTranslators.includes(translator) ? i18n("mulkeys_help") : ""
mulkeysTranslators.includes(translator)
? i18n("mulkeys_help")
: ""
}
/>
</>

View File

@@ -119,11 +119,9 @@ export default function Popup({ setShowPopup, translator: tran }) {
const commands = {};
if (isExt) {
const res = await sendBgMsg(MSG_COMMAND_SHORTCUTS);
if (!res.error) {
res.data.forEach(({ name, shortcut }) => {
res.forEach(({ name, shortcut }) => {
commands[name] = shortcut;
});
}
} else {
const shortcuts = tran.setting.shortcuts;
if (shortcuts) {