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( browser.runtime.onMessage.addListener(async ({ action, args }) => {
({ action, args }, sender, sendResponse) => {
switch (action) { switch (action) {
case MSG_FETCH: case MSG_FETCH:
const { input, opts } = args; const { input, opts } = args;
fetchData(input, opts) return await fetchData(input, opts);
.then((data) => {
sendResponse({ data });
})
.catch((error) => {
sendResponse({ error: error.message, cause: error.cause });
});
break;
case MSG_FETCH_LIMIT: case MSG_FETCH_LIMIT:
const { interval, limit } = args; const { interval, limit } = args;
fetchPool.update(interval, limit); return fetchPool.update(interval, limit);
sendResponse({ data: "ok" });
break;
case MSG_FETCH_CLEAR: case MSG_FETCH_CLEAR:
fetchPool.clear(); return fetchPool.clear();
sendResponse({ data: "ok" });
break;
case MSG_OPEN_OPTIONS: case MSG_OPEN_OPTIONS:
browser.runtime.openOptionsPage(); return await browser.runtime.openOptionsPage();
sendResponse({ data: "ok" });
break;
case MSG_SAVE_RULE: case MSG_SAVE_RULE:
saveRule(args); return await saveRule(args);
sendResponse({ data: "ok" });
break;
case MSG_INJECT_JS: case MSG_INJECT_JS:
getCurTabId() return await browser.scripting.executeScript({
.then((tabId) => target: { tabId: await getCurTabId(), allFrames: true },
browser.scripting.executeScript({
target: { tabId: tabId, allFrames: true },
func: injectInlineJs, func: injectInlineJs,
args: [args], args: [args],
world: "MAIN", world: "MAIN",
})
)
.then(() => {
sendResponse({ data: "ok" });
})
.catch((error) => {
sendResponse({ error: error.message });
}); });
break;
case MSG_INJECT_CSS: case MSG_INJECT_CSS:
getCurTabId() return await browser.scripting.executeScript({
.then((tabId) => target: { tabId: await getCurTabId(), allFrames: true },
browser.scripting.executeScript({
target: { tabId: tabId, allFrames: true },
func: injectInternalCss, func: injectInternalCss,
args: [args], args: [args],
world: "MAIN", world: "MAIN",
})
)
.then(() => {
sendResponse({ data: "ok" });
})
.catch((error) => {
sendResponse({ error: error.message });
}); });
break;
case MSG_CONTEXT_MENUS: case MSG_CONTEXT_MENUS:
const { contextMenuType } = args; return await addContextMenus(args.contextMenuType);
addContextMenus(contextMenuType);
sendResponse({ data: "ok" });
break;
case MSG_COMMAND_SHORTCUTS: case MSG_COMMAND_SHORTCUTS:
browser.commands return await browser.commands.getAll();
.getAll()
.then((commands) => {
sendResponse({ data: commands });
})
.catch((error) => {
sendResponse({ error: error.message });
});
break;
default: 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) { if (!res?.ok) {
const cause = { const msg = {
url: input,
status: res.status, status: res.status,
}; };
if (res.headers.get("Content-Type")?.includes("json")) { 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()) { if (isExt && !isBg()) {
const res = await sendBgMsg(MSG_FETCH, { input, opts }); return await sendBgMsg(MSG_FETCH, { input, opts });
if (res.error) {
throw new Error(res.error, { cause: res.cause });
}
return res.data;
} }
// 油猴/网页/BackgroundPage // 油猴/网页/BackgroundPage
@@ -196,10 +193,7 @@ export const fetchPolyfill = async (input, opts) => {
*/ */
export const updateFetchPool = async (interval, limit) => { export const updateFetchPool = async (interval, limit) => {
if (isExt) { if (isExt) {
const res = await sendBgMsg(MSG_FETCH_LIMIT, { interval, limit }); await sendBgMsg(MSG_FETCH_LIMIT, { interval, limit });
if (res.error) {
throw new Error(res.error);
}
} else { } else {
fetchPool.update(interval, limit); fetchPool.update(interval, limit);
} }
@@ -210,10 +204,7 @@ export const updateFetchPool = async (interval, limit) => {
*/ */
export const clearFetchPool = async () => { export const clearFetchPool = async () => {
if (isExt) { if (isExt) {
const res = await sendBgMsg(MSG_FETCH_CLEAR); await sendBgMsg(MSG_FETCH_CLEAR);
if (res.error) {
throw new Error(res.error);
}
} else { } else {
fetchPool.clear(); fetchPool.clear();
} }

View File

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

View File

@@ -50,16 +50,22 @@ function TestButton({ translator, api }) {
alert.success(i18n("test_success")); alert.success(i18n("test_success"));
} catch (err) { } catch (err) {
// alert.error(`${i18n("test_failed")}: ${err.message}`); // 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( alert.error(
<> <>
<div>{`${i18n("test_failed")}: ${err.message}`}</div> <div>{i18n("test_failed")}</div>
<pre <pre
style={{ style={{
maxWidth: 400, maxWidth: 400,
overflow: "auto", overflow: "auto",
}} }}
> >
{JSON.stringify(err.cause || {}, null, 2)} {msg}
</pre> </pre>
</> </>
); );
@@ -124,7 +130,9 @@ function ApiFields({ translator }) {
onChange={handleChange} onChange={handleChange}
multiline={mulkeysTranslators.includes(translator)} multiline={mulkeysTranslators.includes(translator)}
helperText={ 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 = {}; const commands = {};
if (isExt) { if (isExt) {
const res = await sendBgMsg(MSG_COMMAND_SHORTCUTS); const res = await sendBgMsg(MSG_COMMAND_SHORTCUTS);
if (!res.error) { res.forEach(({ name, shortcut }) => {
res.data.forEach(({ name, shortcut }) => {
commands[name] = shortcut; commands[name] = shortcut;
}); });
}
} else { } else {
const shortcuts = tran.setting.shortcuts; const shortcuts = tran.setting.shortcuts;
if (shortcuts) { if (shortcuts) {