feat: 浏览器扩展完全支持热更新

This commit is contained in:
2026-08-16 20:46:07 +08:00
parent 481518500e
commit 9568e7ac08
21 changed files with 558 additions and 94 deletions
+91 -3
View File
@@ -1,15 +1,103 @@
/**
* Background Service Worker:生命周期与消息转发占位。
* 第一阶段业务请求由 Popup 直接发起;Content 由 Manifest 注入。
* Background:向页面 MAIN world 注入远程功能脚本并调用 mount/unmount。
* chrome.scripting + world:MAIN 可绕过页面 CSP(inline script 会被拦)。
*/
type InjectMessage = {
type: 'INJECT_MAIN_SCRIPT';
payload: { code: string };
};
type CallMessage = {
type: 'CALL_MAIN_FEATURE';
payload: { featureId: string; action: 'mount' | 'unmount' };
};
type BgMessage = InjectMessage | CallMessage | { type: 'BACKGROUND_PING' };
chrome.runtime.onInstalled.addListener(() => {
console.info('[ecbi-extension] installed');
});
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
chrome.runtime.onMessage.addListener((message: BgMessage, sender, sendResponse) => {
if (message?.type === 'BACKGROUND_PING') {
sendResponse({ ok: true, data: { pong: true } });
return true;
}
const tabId = sender.tab?.id;
if (tabId == null) {
sendResponse({ ok: false, message: '缺少 tabId(仅 Content Script 可请求注入)' });
return true;
}
if (message?.type === 'INJECT_MAIN_SCRIPT') {
void chrome.scripting
.executeScript({
target: { tabId },
world: 'MAIN',
func: (source: string) => {
// 扩展注入的 MAIN world 函数内执行,不受页面 CSP 限制
const run = new Function(source);
run();
},
args: [message.payload.code],
})
.then(() => sendResponse({ ok: true }))
.catch((error: unknown) => {
sendResponse({
ok: false,
message: error instanceof Error ? error.message : '注入脚本失败',
});
});
return true;
}
if (message?.type === 'CALL_MAIN_FEATURE') {
const { featureId, action } = message.payload;
void chrome.scripting
.executeScript({
target: { tabId },
world: 'MAIN',
func: async (id: string, act: 'mount' | 'unmount') => {
const bag = (
globalThis as typeof globalThis & {
__ECBI_FEATURES__?: Record<
string,
{
mount?: () => void | Promise<void>;
unmount?: () => void | Promise<void>;
}
>;
}
).__ECBI_FEATURES__;
const mod = bag?.[id];
if (!mod) {
throw new Error(`功能未注册:${id}`);
}
if (act === 'mount') {
if (typeof mod.mount !== 'function') {
throw new Error(`功能无 mount:${id}`);
}
await mod.mount();
return;
}
if (typeof mod.unmount !== 'function') {
throw new Error(`功能无 unmount:${id}`);
}
await mod.unmount();
},
args: [featureId, action],
})
.then(() => sendResponse({ ok: true }))
.catch((error: unknown) => {
sendResponse({
ok: false,
message: error instanceof Error ? error.message : '调用功能失败',
});
});
return true;
}
return false;
});