diff --git a/packages/chrome-extension-mock/tab.ts b/packages/chrome-extension-mock/tab.ts index 8c4cb8f5a..29601414c 100644 --- a/packages/chrome-extension-mock/tab.ts +++ b/packages/chrome-extension-mock/tab.ts @@ -53,4 +53,11 @@ export default class MockTab { this.hook.addListener("remove", callback); }, }; + + // 由测试通过 hook.emit("replace", addedTabId, removedTabId) 触发 + onReplaced = { + addListener: (callback: any) => { + this.hook.addListener("replace", callback); + }, + }; } diff --git a/packages/message/extension_message.test.ts b/packages/message/extension_message.test.ts new file mode 100644 index 000000000..24c225782 --- /dev/null +++ b/packages/message/extension_message.test.ts @@ -0,0 +1,41 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { ExtensionContentMessageSend } from "./extension_message"; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("ExtensionContentMessageSend.notify", () => { + // 回调形式下接收端不回包,Chrome 会报 lastError「The message port closed before a response was received」; + // Promise 形式则正常 resolve(Chrome 156 实测),所以单向通知不能带回调 + it("不带回调发送,并把定向选项原样交给 tabs.sendMessage", async () => { + const spy = vi.spyOn(chrome.tabs, "sendMessage"); + const msg = { action: "scripting/runtime/valueUpdates", data: [] }; + + await expect(new ExtensionContentMessageSend(7, { frameId: 0, documentId: "doc" }).notify(msg)).resolves.toBe( + undefined + ); + await new ExtensionContentMessageSend(8).notify(msg); + + expect(spy.mock.calls).toEqual([ + [7, msg, { frameId: 0, documentId: "doc" }], + [8, msg], + ]); + }); + + it("接收端不存在时以浏览器的错误拒绝", async () => { + const error = new Error("Could not establish connection. Receiving end does not exist."); + vi.spyOn(chrome.tabs, "sendMessage").mockImplementation((() => Promise.reject(error)) as never); + + await expect(new ExtensionContentMessageSend(7).notify({ action: "a" })).rejects.toBe(error); + }); + + it("调用本身被拒(如消息超过 64 MiB)时与 chrome API 一样同步抛出,而不是返回被拒绝的 Promise", () => { + const error = new Error("Message exceeded maximum allowed size of 64MiB."); + vi.spyOn(chrome.tabs, "sendMessage").mockImplementation((() => { + throw error; + }) as never); + + expect(() => new ExtensionContentMessageSend(7).notify({ action: "a" })).toThrow(error); + }); +}); diff --git a/packages/message/extension_message.ts b/packages/message/extension_message.ts index e0702c98f..a3cea090b 100644 --- a/packages/message/extension_message.ts +++ b/packages/message/extension_message.ts @@ -240,6 +240,18 @@ export class ExtensionContentMessageSend implements MessageSend { } ) {} + /** + * 单向通知,配合接收端的 Server.onNotify。不能带回调:接收端不回包时回调形式必有 lastError, + * Promise 形式则在接收端的监听执行完后 resolve。目标不存在时 reject;调用本身被拒(如消息超过 64 MiB)时 + * 与 chrome API 一样同步抛出。调用方依赖这一区分判断目标是否还在,所以这里不能改成 async 函数。 + */ + notify(data: TMessage): Promise { + const sent = this.options + ? chrome.tabs.sendMessage(this.tabId, data, this.options) + : chrome.tabs.sendMessage(this.tabId, data); + return sent.then(() => undefined); + } + sendMessage(data: TMessage): Promise { return new Promise((resolve) => { if (!this.options?.documentId && !this.options?.frameId) { diff --git a/packages/message/server.test.ts b/packages/message/server.test.ts index 27061cf3e..086294dd8 100644 --- a/packages/message/server.test.ts +++ b/packages/message/server.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, beforeEach, vi, afterEach } from "vitest"; import { GetSenderType, SenderConnect, SenderRuntime, Server, type IGetSender } from "./server"; import { CustomEventMessage } from "./custom_event_message"; -import type { MessageConnect, RuntimeMessageSender } from "./types"; +import type { Message, MessageConnect, OnMessageCallback, RuntimeMessageSender } from "./types"; import { uuidv4 } from "@App/pkg/utils/uuid"; let inboundMessage: CustomEventMessage; @@ -658,4 +658,62 @@ describe("Server", () => { expect(response.data).toBeUndefined(); }); }); + describe("onNotify 单向通知", () => { + // 直接拿到传输层的 onMessage 回调:要观察的正是回调的返回值与 sendResponse 是否被调用, + // 这决定了 chrome.runtime 是否为这条消息保留响应通道并回传一条回包 + const setupNotifyServer = () => { + let onMessage: OnMessageCallback | undefined; + const transport = { + onMessage: (cb: OnMessageCallback) => { + onMessage = cb; + }, + onConnect: () => {}, + } as unknown as Message; + const notifyServer = new Server("api", transport); + const sender = { tab: { id: 3 }, frameId: 2 } as RuntimeMessageSender; + return { + notifyServer, + sender, + deliver: (msg: any, sendResponse: () => void) => onMessage!(msg, sendResponse, sender), + }; + }; + + it("调用处理器,但不回包,也不保留响应通道", () => { + const { notifyServer, deliver, sender } = setupNotifyServer(); + const handler = vi.fn(); + notifyServer.onNotify("updates", handler); + const sendResponse = vi.fn(); + + const keepChannel = deliver({ action: "api/updates", data: [1, 2] }, sendResponse); + + expect(handler).toHaveBeenCalledWith([1, 2], expect.any(SenderRuntime)); + expect((handler.mock.calls[0][1] as SenderRuntime).getSender()).toBe(sender); + expect(sendResponse).not.toHaveBeenCalled(); + expect(keepChannel).toBe(false); + }); + + it("处理器抛错或返回的 Promise 被拒绝时,同样不回包", async () => { + const { notifyServer, deliver } = setupNotifyServer(); + notifyServer.onNotify("throws", () => { + throw new Error("sync failure"); + }); + notifyServer.onNotify("rejects", () => Promise.reject(new Error("async failure"))); + const sendResponse = vi.fn(); + + expect(deliver({ action: "api/throws", data: {} }, sendResponse)).toBe(false); + expect(deliver({ action: "api/rejects", data: {} }, sendResponse)).toBe(false); + await nextTick(); + + expect(sendResponse).not.toHaveBeenCalled(); + }); + + it("与 on 注册的处理器同名时抛错", () => { + const { notifyServer } = setupNotifyServer(); + notifyServer.on("dup", vi.fn()); + notifyServer.onNotify("dup2", vi.fn()); + + expect(() => notifyServer.onNotify("dup", vi.fn())).toThrow("duplicate message handler: api/dup"); + expect(() => notifyServer.on("dup2", vi.fn())).toThrow("duplicate message handler: api/dup2"); + }); + }); }); diff --git a/packages/message/server.ts b/packages/message/server.ts index ee53e4fd8..ec0671934 100644 --- a/packages/message/server.ts +++ b/packages/message/server.ts @@ -111,6 +111,7 @@ export class SenderRuntime { type ApiFunction = (params: any, con: IGetSender) => Promise | any | void; type ApiFunctionSync = (params: any, con: IGetSender) => any; +type NotifyFunction = (params: any, con: IGetSender) => void | Promise; type MiddlewareFunction = (params: any, con: IGetSender, next: () => Promise | any) => Promise | any; const formatErrorToClient = (e: any) => { @@ -128,6 +129,7 @@ const formatErrorToClient = (e: any) => { export class Server { private apiFunctionMap: Map = new Map(); + private notifyFunctionMap: Map = new Map(); private logger = LoggerCore.getInstance().logger({ service: "messageServer" }); @@ -155,7 +157,10 @@ export class Server { if (typeof msg.action !== "string") return; this.logger.trace("server onMessage", { msg: msg as any }); if (msg.action?.startsWith(prefix)) { - return this.messageHandle(msg.action.slice(prefix.length + 1), msg.data, sendResponse, sender); + const action = msg.action.slice(prefix.length + 1); + const notify = this.notifyFunctionMap.get(action); + if (notify) return this.notifyHandle(action, notify, msg.data, sender); + return this.messageHandle(action, msg.data, sendResponse, sender); } }); return false; @@ -167,10 +172,35 @@ export class Server { } on(name: string, func: ApiFunction) { - if (this.apiFunctionMap.has(name)) { + this.assertNotRegistered(name); + this.apiFunctionMap.set(name, func); + } + + /** + * 注册单向通知:不回包,监听回调返回 false,发送端不必为它保留响应通道。 + * 回包本身就是一次进程间消息,高频的一对多推送(如值更新)不需要回执时用它。 + */ + onNotify(name: string, func: NotifyFunction) { + this.assertNotRegistered(name); + this.notifyFunctionMap.set(name, func); + } + + private assertNotRegistered(name: string) { + if (this.apiFunctionMap.has(name) || this.notifyFunctionMap.has(name)) { throw new Error(`duplicate message handler: ${this.prefix}/${name}`); } - this.apiFunctionMap.set(name, func); + } + + private notifyHandle(action: string, func: NotifyFunction, params: any, sender: RuntimeMessageSender): false { + try { + const ret = func(params, new SenderRuntime(sender)); + if (ret instanceof Promise) { + ret.catch((e: Error) => this.logger.error("notifyHandle error", { action }, Logger.E(e))); + } + } catch (e: any) { + this.logger.error("notifyHandle error", { action }, Logger.E(e)); + } + return false; } private connectHandle(msg: string, params: any, con: MessageConnect) { diff --git a/src/app/cache_key.ts b/src/app/cache_key.ts index 7cd921201..0c57657f1 100644 --- a/src/app/cache_key.ts +++ b/src/app/cache_key.ts @@ -5,3 +5,5 @@ export const CACHE_KEY_TAB_LOADED = "tabLoaded:"; export const CACHE_KEY_SET_VALUE = "setValue:"; export const CACHE_KEY_PERMISSION = "permission:"; export const CACHE_KEY_SKILL_INSTALL = "skillInstall:"; // Skill ZIP 待安装数据缓存 +// 值更新投递表:某 tab 里各 frame 运行着哪些 storageName,SW 重启后据此恢复 +export const CACHE_KEY_VALUE_UPDATE_TARGETS = "valueUpdateTargets:"; diff --git a/src/app/service/content/gm_api/gm_api.test.ts b/src/app/service/content/gm_api/gm_api.test.ts index d09336d0a..d463fef33 100644 --- a/src/app/service/content/gm_api/gm_api.test.ts +++ b/src/app/service/content/gm_api/gm_api.test.ts @@ -689,6 +689,46 @@ describe.concurrent("GM_value", () => { }); }); + // 不属于任何标签页的 frame(如扩展页面里内嵌的网页)无法用 tabs.sendMessage 投递,SW 把本次更新随应答带回; + // 否则 GM.setValue 的 Promise 永远等不到回执 + it.concurrent.each(["GM.setValue", "GM.setValues"])( + "%s 的应答带回本次更新时,Promise 完成并触发本脚本的监听", + async (api) => { + const script = Object.assign({}, scriptRes, { value: {} }) as ScriptLoadInfo; + script.metadata = { ...script.metadata, grant: [api, "GM_addValueChangeListener"] }; + const call = api === "GM.setValue" ? `GM.setValue("k", "v")` : `GM.setValues({ k: "v" })`; + script.code = ` + const changes = []; + GM_addValueChangeListener("k", (name, oldValue, newValue, remote) => changes.push([name, oldValue, newValue, remote])); + await ${call}; + return changes; + `; + const mockSendMessage = vi + .fn() + .mockImplementation(async (msg: { data: { params: [string]; runFlag: string } }) => ({ + code: 0, + data: { + id: msg.data.params[0], + entries: [["k", encodeRValue("v"), encodeRValue(undefined)]], + uuid: script.uuid, + storageName: script.uuid, + sender: { runFlag: msg.data.runFlag, tabId: -1 }, + valueUpdated: true, + }, + })); + const exec = new ExecScript(script, { + envPrefix: "scripting", + message: { sendMessage: mockSendMessage } as unknown as Message, + contentMsg: undefined as any, + code: nilFn, + envInfo, + }); + exec.scriptFunc = compileScript(compileScriptCode(script)); + + await expect(exec.exec()).resolves.toEqual([["k", undefined, "v", false]]); + } + ); + it.concurrent("value引用问题 #1141", async () => { const script = Object.assign({}, scriptRes) as ScriptLoadInfo; script.value = {}; diff --git a/src/app/service/content/gm_api/gm_api.ts b/src/app/service/content/gm_api/gm_api.ts index d9c52c8e4..e2e0df99e 100644 --- a/src/app/service/content/gm_api/gm_api.ts +++ b/src/app/service/content/gm_api/gm_api.ts @@ -280,6 +280,12 @@ export default class GMApi extends GM_Base { }); } + // 不属于任何标签页的 frame(如扩展页面里内嵌的网页)收不到 SW 的 tabs.sendMessage 投递, + // SW 会把本次更新随应答带回;其他 frame 的应答不带,回执仍由投递的值更新完成 + static applyOwnValueUpdate(a: GMApi, update: unknown) { + if (update) a.valueUpdate(update as ValueUpdateDataEncoded); + } + static _GM_setValue(a: GMApi, promise: any, key: string, value: any) { key = `${key}`; if (!a.scriptRes) return; @@ -292,9 +298,10 @@ export default class GMApi extends GM_Base { if (promise) { valueChangePromiseMap.set(id, promise); } + let sent: Promise; if (value === undefined) { delete a.scriptRes.value[key]; - a.sendMessage("GM_setValue", [id, key]); + sent = a.sendMessage("GM_setValue", [id, key]); } else { // 对object的value进行一次转化 if (value && typeof value === "object") { @@ -303,11 +310,12 @@ export default class GMApi extends GM_Base { // customClone 可能返回 undefined a.scriptRes.value[key] = value; if (value === undefined) { - a.sendMessage("GM_setValue", [id, key]); + sent = a.sendMessage("GM_setValue", [id, key]); } else { - a.sendMessage("GM_setValue", [id, key, value]); + sent = a.sendMessage("GM_setValue", [id, key, value]); } } + sent.then((update) => applyOwnValueUpdate(a, update)); return id; } @@ -339,7 +347,7 @@ export default class GMApi extends GM_Base { // 避免undefined 等空值流失,先进行映射处理 keyValuePairs.push([key, encodeRValue(value_)]); } - a.sendMessage("GM_setValues", [id, keyValuePairs]); + a.sendMessage("GM_setValues", [id, keyValuePairs]).then((update) => applyOwnValueUpdate(a, update)); return id; } @@ -1631,4 +1639,5 @@ export default class GMApi extends GM_Base { export const { createGMBase } = GM_Base; // 从 GMApi 对象中解构出内部函数,用于后续本地使用,不导出 -const { _GM_getValue, _GM_cookie, _GM_setValue, _GM_setValues, _GM_download, _GM_notification } = GMApi; +const { _GM_getValue, _GM_cookie, _GM_setValue, _GM_setValues, _GM_download, _GM_notification, applyOwnValueUpdate } = + GMApi; diff --git a/src/app/service/content/scripting.test.ts b/src/app/service/content/scripting.test.ts new file mode 100644 index 000000000..306db97ef --- /dev/null +++ b/src/app/service/content/scripting.test.ts @@ -0,0 +1,167 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { Server } from "@Packages/message/server"; +import type { MessageSend } from "@Packages/message/types"; +import type { CustomEventMessage } from "@Packages/message/custom_event_message"; +import ScriptingRuntime from "./scripting"; +import type { ValueUpdateDataEncoded } from "./types"; + +type Handler = (data: any) => any; + +const createServer = () => { + const handlers = new Map(); + const notifies = new Map(); + return { + server: { + on: (name: string, fn: Handler) => handlers.set(name, fn), + onNotify: (name: string, fn: Handler) => notifies.set(name, fn), + } as unknown as Server, + handlers, + notifies, + }; +}; + +const createPageSender = () => { + const sendMessage = vi.fn().mockResolvedValue({ code: 0, data: undefined }); + return { sender: { sendMessage } as unknown as CustomEventMessage, sendMessage }; +}; + +const valueUpdate = (storageName: string): ValueUpdateDataEncoded => ({ + id: "id-1", + entries: [["k", "v", undefined] as any], + uuid: "uuid-1", + storageName, + sender: { runFlag: "", tabId: 1 }, + valueUpdated: true, +}); + +const actionsOf = (fn: ReturnType) => fn.mock.calls.map(([msg]) => msg.action); + +const setup = (pageLoadData?: unknown) => { + const ext = createServer(); + const page = createServer(); + const toContent = createPageSender(); + const toInject = createPageSender(); + const toExt = vi.fn().mockResolvedValue({ code: 0, data: pageLoadData ?? { ok: false } }); + const senderToExt = { sendMessage: toExt } as unknown as MessageSend; + const runtime = new ScriptingRuntime(ext.server, page.server, senderToExt, toContent.sender, toInject.sender); + runtime.init(); + const valueUpdates = (list: ValueUpdateDataEncoded[]) => ext.notifies.get("runtime/valueUpdates")!(list); + return { runtime, ext, toContent, toInject, toExt, valueUpdates }; +}; + +const loadedPage = { + ok: true, + injectScriptList: [{ uuid: "a", metadata: { storagename: ["page-store"] } }], + contentScriptList: [{ uuid: "b", metadata: { storagename: ["content-store"] } }], + envInfo: {}, +}; + +describe("ScriptingRuntime 值更新投递", () => { + let storageListeners: Array<(changes: Record) => void>; + let originalOnChanged: unknown; + + beforeEach(() => { + storageListeners = []; + originalOnChanged = (chrome.storage.local as any).onChanged; + (chrome.storage.local as any).onChanged = { + addListener: (fn: (typeof storageListeners)[number]) => storageListeners.push(fn), + }; + }); + + afterEach(() => { + (chrome.storage.local as any).onChanged = originalOnChanged; + }); + + // 每个页面的每个 frame 都有 scripting.js;若它监听 storage.local,任何一次 local 写入 + // (包括整包 value:*)的新旧值都会被序列化投递到所有 frame,见 #1834。 + it("chrome.storage.local 的变化不会被转发给页面", async () => { + const { toContent, toInject } = setup(); + + for (const fn of storageListeners) { + fn({ + valueUpdateDelivery: { newValue: { rId: "1", sendData: valueUpdate("s1") } }, + "value:s1": { newValue: { data: { k: "v" } }, oldValue: { data: {} } }, + }); + } + await Promise.resolve(); + + expect(storageListeners).toHaveLength(0); + expect(toContent.sendMessage).not.toHaveBeenCalled(); + expect(toInject.sendMessage).not.toHaveBeenCalled(); + }); + + it("pageLoad 之后,批量更新逐条按 storageName 只转发给运行它的一侧", async () => { + const { runtime, toContent, toInject, valueUpdates } = setup(loadedPage); + runtime.pageLoad(); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage)).toContain("inject/pageLoad")); + toContent.sendMessage.mockClear(); + toInject.sendMessage.mockClear(); + + valueUpdates([valueUpdate("page-store"), valueUpdate("other-store"), valueUpdate("content-store")]); + + expect(toInject.sendMessage.mock.calls.map(([msg]) => [msg.action, msg.data.storageName])).toEqual([ + ["inject/runtime/valueUpdate", "page-store"], + ]); + expect(toContent.sendMessage.mock.calls.map(([msg]) => [msg.action, msg.data.storageName])).toEqual([ + ["content/runtime/valueUpdate", "content-store"], + ]); + }); + + it("pageLoad 尚未返回时,更新同时转发给 page 与 content", () => { + const { toContent, toInject, valueUpdates } = setup(); + + valueUpdates([valueUpdate("any-store")]); + + expect(actionsOf(toContent.sendMessage)).toEqual(["content/runtime/valueUpdate"]); + expect(actionsOf(toInject.sendMessage)).toEqual(["inject/runtime/valueUpdate"]); + }); +}); + +describe("ScriptingRuntime bfcache 还原上报", () => { + const pageShowCalls = (toExt: ReturnType) => + toExt.mock.calls.filter(([msg]) => msg.action.endsWith("/pageShow")).map(([msg]) => msg.data); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + // 离开页面时,新页面的 pageLoad 已清掉本页的值更新投递登记;还原后要带上仍在运行的 storageName 重新登记 + it.each([ + ["顶层 frame", true], + ["子 frame", false], + ])("%s 运行着脚本时,pageShow 带上它运行的 storageName", async (_label, isTop) => { + if (!isTop) vi.spyOn(window, "top", "get").mockReturnValue({} as Window); + const { runtime, toExt, toInject } = setup(loadedPage); + runtime.pageLoad(); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage)).toContain("inject/pageLoad")); + + window.dispatchEvent(Object.assign(new Event("pageshow"), { persisted: true })); + + expect(pageShowCalls(toExt)).toEqual([{ storageNames: ["page-store", "content-store"] }]); + }); + + it("子 frame 没有运行脚本时不上报;顶层 frame 仍要上报(Popup 据此判断本页扩展触及得到)", async () => { + vi.spyOn(window, "top", "get").mockReturnValue({} as Window); + const sub = setup({ ok: false }); + sub.runtime.pageLoad(); + vi.restoreAllMocks(); + const top = setup({ ok: false }); + top.runtime.pageLoad(); + await vi.waitFor(() => expect(top.toExt).toHaveBeenCalled()); + + window.dispatchEvent(Object.assign(new Event("pageshow"), { persisted: true })); + + expect(pageShowCalls(sub.toExt)).toEqual([]); + expect(pageShowCalls(top.toExt)).toEqual([{ storageNames: [] }]); + }); + + it("普通的 pageshow(非 bfcache 还原)不上报", async () => { + const { runtime, toExt, toInject } = setup(loadedPage); + runtime.pageLoad(); + await vi.waitFor(() => expect(actionsOf(toInject.sendMessage)).toContain("inject/pageLoad")); + + window.dispatchEvent(Object.assign(new Event("pageshow"), { persisted: false })); + + expect(pageShowCalls(toExt)).toEqual([]); + }); +}); diff --git a/src/app/service/content/scripting.ts b/src/app/service/content/scripting.ts index 7286d82b0..fa8ae6a83 100644 --- a/src/app/service/content/scripting.ts +++ b/src/app/service/content/scripting.ts @@ -6,6 +6,7 @@ import { RuntimeClient } from "../service_worker/client"; import { getStorageName, makeBlobURL } from "@App/pkg/utils/utils"; import type { Logger } from "@App/app/repo/logger"; import LoggerCore from "@App/app/logger/core"; +import LoggerUtil from "@App/app/logger/logger"; import type { ValueUpdateDataEncoded } from "./types"; const PageOrContent = { @@ -16,11 +17,6 @@ const PageOrContent = { type PageOrContent = ValueOf; -// For Firefox, StorageArea.setAccessLevel is not implemented. -// See https://bugzilla.mozilla.org/show_bug.cgi?id=1724754 -// const deliveryStorage = isFirefox() ? chrome.storage.local : chrome.storage.session; -const deliveryStorage = chrome.storage.local; // 日后再处理 - // scripting页的处理 export default class ScriptingRuntime { private activeStorageNames: Map | null = null; @@ -54,36 +50,24 @@ export default class ScriptingRuntime { // 转发给inject和content return this.broadcastToPage("runtime/emitEvent", data); }); - this.extServer.on("runtime/valueUpdate", (data) => { - // 转发给inject和content - return this.broadcastToPage("runtime/valueUpdate", data); - }); - this.server.on("logger", (data: Logger) => { - LoggerCore.logger().log(data.level, data.message, data.label); - }); - - // ================================ - // 来自 service_worker 的投递:storage 广播(类似 UDP) - // ================================ - - // 接收 service_worker 的 chrome.storage.local 值改变通知 (一对多广播) - // 类似 UDP 原理,service_worker 不会有任何「等待处理」 - // 由于 changes 会包括新旧值 (Chrome: JSON serialization, Firefox: Structured Clone) - // 因此需要注意资讯量不要过大导致 onChanged 的触发过慢 - deliveryStorage.onChanged.addListener((changes) => { - const record = changes["valueUpdateDelivery"]; - if (record?.newValue) { - const sendData = (record.newValue as { sendData: ValueUpdateDataEncoded }).sendData; + // 单向通知:SW 不需要回执(GM.setValue 的回执靠更新里的 id),省掉每个 frame 的一次回包 + this.extServer.onNotify("runtime/valueUpdates", (list: ValueUpdateDataEncoded[]) => { + for (const data of list) { + // SW 整页投递时,没有运行该脚本的 frame 也会收到,需按 storageName 过滤; + // pageLoad 返回前还不知道本 frame 运行哪些脚本,两侧都转发 const activeOn = this.activeStorageNames === null ? PageOrContent.PAGE_AND_CONTENT - : this.activeStorageNames.get(sendData.storageName); - if (activeOn) { - // 转发给 content 和 inject - this.broadcastToPage("runtime/valueUpdate", sendData, activeOn); - } + : this.activeStorageNames.get(data.storageName); + if (!activeOn) continue; + this.broadcastToPage("runtime/valueUpdate", data, activeOn).catch((e) => { + LoggerCore.logger().error("forward value update failed", { storageName: data.storageName }, LoggerUtil.E(e)); + }); } }); + this.server.on("logger", (data: Logger) => { + LoggerCore.logger().log(data.level, data.message, data.label); + }); forwardMessage("serviceWorker", "script/isInstalled", this.server, this.senderToExt); forwardMessage( @@ -148,14 +132,15 @@ export default class ScriptingRuntime { pageLoad() { const client = new RuntimeClient(this.senderToExt); - // bfcache 还原不会重新执行 content script,pageLoad 因此只发生一次; - // 但页面里的脚本仍在运行,需要补一次上报,否则 Popup 会误判本页没有脚本在跑。 - // 只有顶层 frame 参与判定,子 frame 不必上报。 - if (window.top === window) { - window.addEventListener("pageshow", (e) => { - if (e.persisted) client.pageShow(); - }); - } + // bfcache 还原不会重新执行 content script,pageLoad 因此只发生一次;但页面里的脚本仍在运行,需要补一次上报: + // 顶层 frame 让 Popup 不误判本页没有脚本在跑;运行着脚本的每个 frame 都带上 storageName, + // 重新登记值更新投递(离开本页时已被新页面的 pageLoad 清掉) + const isTop = window.top === window; + window.addEventListener("pageshow", (e) => { + if (!e.persisted) return; + const storageNames = this.activeStorageNames ? [...this.activeStorageNames.keys()] : []; + if (isTop || storageNames.length) client.pageShow(storageNames); + }); // 向service_worker请求脚本列表及环境信息 client.pageLoad().then((o) => { if (!o.ok) return; diff --git a/src/app/service/content/types.ts b/src/app/service/content/types.ts index 87962e4a4..ae8c2d96b 100644 --- a/src/app/service/content/types.ts +++ b/src/app/service/content/types.ts @@ -7,6 +7,9 @@ export type ScriptFunc = (named: { [key: string]: any } | undefined, scriptName: export type ValueUpdateSender = { runFlag: string; tabId?: number; + // 发起写入的 frame。发起方可能还没在投递表里登记(页面早期写值),需要据此单独投递回执 + frameId?: number; + documentId?: string; }; /** diff --git a/src/app/service/service_worker/client.ts b/src/app/service/service_worker/client.ts index 27ca0a303..84caa079c 100644 --- a/src/app/service/service_worker/client.ts +++ b/src/app/service/service_worker/client.ts @@ -353,9 +353,9 @@ export class RuntimeClient extends Client { return this.doThrow("pageLoad"); } - /** bfcache 还原上报:只告知本页仍在运行,不请求脚本 */ - pageShow() { - return this.do("pageShow"); + /** bfcache 还原上报:告知本页仍在运行及本 frame 运行的 storageName,不请求脚本 */ + pageShow(storageNames: string[]) { + return this.do("pageShow", { storageNames }); } scriptLoad(flag: string, uuid: string) { diff --git a/src/app/service/service_worker/gm_api/gm_api.test.ts b/src/app/service/service_worker/gm_api/gm_api.test.ts index f05fd6793..cafbc93ae 100644 --- a/src/app/service/service_worker/gm_api/gm_api.test.ts +++ b/src/app/service/service_worker/gm_api/gm_api.test.ts @@ -145,6 +145,52 @@ describe("window.focus", () => { }); }); +// 发起写入的 document 可能还没在值更新投递表里登记(页面早期写值), +// 需要靠 sender 上的 frame 信息单独投递回执,否则该页的 GM.setValue Promise 等不到完成 +describe.each(["GM_setValue", "GM_setValues"] as const)("%s 的写入来源", (api) => { + it("valueSender 带上发起写入的标签页、frame 与 document", async () => { + const setValues = vi.fn().mockResolvedValue(undefined); + const gmApi = Object.create(GMApi.prototype) as GMApi; + (gmApi as unknown as { value: unknown }).value = { setValues }; + const sender = makeSender(); + sender.getSender = () => ({ tab: { id: 11 } as chrome.tabs.Tab, frameId: 3, documentId: "doc-3" }); + const params = api === "GM_setValue" ? ["id-1", "k", "v"] : ["id-1", [["k", "v"]]]; + + await gmApi[api]({ script: { uuid: "uuid-1" }, params, runFlag: "flag" } as never, sender); + + expect(setValues.mock.calls[0][0].valueSender).toEqual({ + runFlag: "flag", + tabId: 11, + frameId: 3, + documentId: "doc-3", + }); + }); + + // 不属于任何标签页的网页 frame(如扩展页面里内嵌的网页)收不到 tabs.sendMessage 投递,本次更新只能随应答带回; + // 标签页里的 frame 由投递送达,后台脚本(offscreen 扩展页)由 offscreen 投递送达,二者都不能再带,否则会处理两遍 + it.each([ + ["不属于任何标签页的网页 frame", { frameId: 0, url: "https://embedded.test/" }, true], + ["tab.id 为 TAB_ID_NONE 的网页 frame", { tab: { id: -1 }, frameId: 0, url: "https://embedded.test/" }, true], + ["标签页里的 frame", { tab: { id: 11 }, frameId: 0, url: "https://page.test/" }, false], + ["offscreen 扩展页(后台脚本)", { frameId: 0, url: "chrome-extension://ext-id/src/offscreen.html" }, false], + ])("%s 发起写入时,应答是否带回本次更新", async (_label, chromeSender, carries) => { + vi.spyOn(chrome.runtime, "getURL").mockImplementation( + ((path: string) => `chrome-extension://ext-id${path}`) as never + ); + const update = { id: "id-1" }; + const gmApi = Object.create(GMApi.prototype) as GMApi; + (gmApi as unknown as { value: unknown }).value = { setValues: vi.fn().mockResolvedValue(update) }; + const sender = makeSender(); + sender.getSender = () => chromeSender as chrome.runtime.MessageSender; + const params = api === "GM_setValue" ? ["id-1", "k", "v"] : ["id-1", [["k", "v"]]]; + + const ret = await gmApi[api]({ script: { uuid: "uuid-1" }, params, runFlag: "flag" } as never, sender); + + expect(ret).toBe(carries ? update : undefined); + vi.restoreAllMocks(); + }); +}); + describe.concurrent("mergeCookieHeader(GM_xmlhttpRequest 非 anonymous 的 cookie 合并)", () => { it.concurrent("同名 cookie 应以脚本自定义值覆盖已有 cookie,而非追加(TM #2754)", () => { const result = mergeCookieHeader("data=2", [{ name: "data", value: "1" }]); diff --git a/src/app/service/service_worker/gm_api/gm_api.ts b/src/app/service/service_worker/gm_api/gm_api.ts index a658951ed..b2b0be3b6 100644 --- a/src/app/service/service_worker/gm_api/gm_api.ts +++ b/src/app/service/service_worker/gm_api/gm_api.ts @@ -250,6 +250,13 @@ export enum SelfMatch { SUB = 2, } +// 不属于任何标签页的网页 frame(如扩展页面里内嵌的网页):tabs.sendMessage 投递不到,值更新只能随 GM_setValue 的应答带回。 +// 扩展自身的页面(offscreen 里的后台脚本)不算:它们由 offscreen 投递送达 +const isTablessPageFrame = (sender: chrome.runtime.MessageSender | undefined) => + !!sender?.url && + !((sender.tab?.id ?? -1) > 0) && + new URL(sender.url).origin !== new URL(chrome.runtime.getURL("/")).origin; + export const getConnectMatched = ( metadataConnect: string[] | undefined, reqURL: URL, @@ -596,11 +603,21 @@ export default class GMApi { } const [id, key, value] = request.params as [string, string, any]; const keyValuePairs = [[key, encodeRValue(value)]] as TKeyValuePair[]; + const chromeSender = sender.getSender(); const valueSender = { runFlag: request.runFlag, - tabId: sender.getSender()?.tab?.id || -1, + tabId: chromeSender?.tab?.id || -1, + frameId: chromeSender?.frameId, + documentId: chromeSender?.documentId, }; - await this.value.setValues({ uuid: request.script.uuid, id, keyValuePairs, isReplace: false, valueSender }); + const update = await this.value.setValues({ + uuid: request.script.uuid, + id, + keyValuePairs, + isReplace: false, + valueSender, + }); + return isTablessPageFrame(chromeSender) ? update : undefined; } @PermissionVerify.API({ link: ["GM_deleteValues"] }) @@ -609,11 +626,21 @@ export default class GMApi { throw new Error("param is failed"); } const [id, keyValuePairs] = request.params; + const chromeSender = sender.getSender(); const valueSender = { runFlag: request.runFlag, - tabId: sender.getSender()?.tab?.id || -1, + tabId: chromeSender?.tab?.id || -1, + frameId: chromeSender?.frameId, + documentId: chromeSender?.documentId, }; - await this.value.setValues({ uuid: request.script.uuid, id, keyValuePairs, isReplace: false, valueSender }); + const update = await this.value.setValues({ + uuid: request.script.uuid, + id, + keyValuePairs, + isReplace: false, + valueSender, + }); + return isTablessPageFrame(chromeSender) ? update : undefined; } @PermissionVerify.API() diff --git a/src/app/service/service_worker/runtime.test.ts b/src/app/service/service_worker/runtime.test.ts index ac35581be..46e37957e 100644 --- a/src/app/service/service_worker/runtime.test.ts +++ b/src/app/service/service_worker/runtime.test.ts @@ -1480,6 +1480,133 @@ describe("pushValueUpdate 判断是否需要为 early-start 脚本重新编译", }); }); +describe("值更新按 pageLoad / pageShow 登记的 document 投递", () => { + const scriptsFor = (...storageNames: string[]) => + ({ + injectScriptList: storageNames.map((name) => ({ uuid: name, metadata: {} })), + contentScriptList: [], + envInfo: {}, + scriptmenus: [], + }) as unknown as Awaited>; + const frameSender = (frameId: number, documentId: string) => + new SenderRuntime({ + id: "scriptcat-test", + url: "https://www.example.com/page", + frameId, + documentId, + tab: { id: 11, incognito: false }, + } as chrome.runtime.MessageSender); + const sendData = (storageName: string) => ({ + id: "id-1", + entries: [], + uuid: "uuid-1", + storageName, + sender: { runFlag: "", tabId: -1 }, + valueUpdated: false, + }); + const sentTargets = (spy: ReturnType) => + spy.mock.calls.map(([tabId, msg, options]: any[]) => [ + tabId, + msg.action, + msg.data.map((d: any) => d.storageName), + options, + ]); + + beforeEach(async () => { + await chrome.storage.session.clear(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + // 不再经 chrome.storage.local 广播:每个 frame 都要监听 local.onChanged,任何一次 local 写入都会扇出到所有 frame(#1834) + it("pageLoad 登记后,值更新以单向通知定向发给该 document,不写 chrome.storage.local", async () => { + const { runtime } = _createRuntimeContext(); + vi.spyOn(runtime, "getScriptsForTab").mockResolvedValue(scriptsFor("a")); + const sendSpy = vi.spyOn(chrome.tabs, "sendMessage"); + const setSpy = vi.spyOn(chrome.storage.local, "set"); + + await runtime.pageLoad(undefined, frameSender(0, "doc-top")); + await runtime.pushValueUpdate(_createMockScript(), sendData("a")); + + expect(sentTargets(sendSpy)).toEqual([ + [11, "scripting/runtime/valueUpdates", ["a"], { frameId: 0, documentId: "doc-top" }], + ]); + expect(setSpy).not.toHaveBeenCalled(); + }); + + it("顶层 frame 的 pageLoad 一到达就清掉旧页面,先于它完成登记的新子 frame 保留", async () => { + const { runtime } = _createRuntimeContext(); + let resolveTop!: (v: Awaited>) => void; + vi.spyOn(runtime, "getScriptsForTab") + .mockResolvedValueOnce(scriptsFor("b")) // 旧页面的子 frame + .mockReturnValueOnce(new Promise((resolve) => (resolveTop = resolve))) // 新页面顶层,较慢 + .mockResolvedValueOnce(scriptsFor("b")); // 新页面的子 frame + const sendSpy = vi.spyOn(chrome.tabs, "sendMessage"); + + await runtime.pageLoad(undefined, frameSender(5, "old-sub")); + const top = runtime.pageLoad(undefined, frameSender(0, "new-top")); + await runtime.pageLoad(undefined, frameSender(9, "new-sub")); + resolveTop(scriptsFor("a")); + await top; + await runtime.pushValueUpdate(_createMockScript(), sendData("b")); + + expect(sentTargets(sendSpy)).toEqual([ + [11, "scripting/runtime/valueUpdates", ["b"], { frameId: 9, documentId: "new-sub" }], + ]); + }); + + // early-start 脚本在 document_start 就已运行,pageLoad 查询脚本期间其他标签页的写入也要送达(main 上 scripting + // 从初始化起就监听,pageLoad 返回前两侧都转发) + it("pageLoad 查询脚本期间,其他标签页的更新也会投递给这个 document", async () => { + const { runtime } = _createRuntimeContext(); + let resolveScripts!: (v: Awaited>) => void; + vi.spyOn(runtime, "getScriptsForTab").mockReturnValue(new Promise((resolve) => (resolveScripts = resolve))); + const sendSpy = vi.spyOn(chrome.tabs, "sendMessage"); + + const loading = runtime.pageLoad(undefined, frameSender(0, "early-doc")); + await runtime.pushValueUpdate(_createMockScript(), sendData("early-store")); + resolveScripts(scriptsFor("early-store")); + await loading; + + expect(sentTargets(sendSpy)).toEqual([ + [11, "scripting/runtime/valueUpdates", ["early-store"], { frameId: 0, documentId: "early-doc" }], + ]); + }); + + it("pageLoad 查完脚本后只投递该 document 实际运行的 storageName", async () => { + const { runtime } = _createRuntimeContext(); + vi.spyOn(runtime, "getScriptsForTab").mockResolvedValue(scriptsFor("a")); + const sendSpy = vi.spyOn(chrome.tabs, "sendMessage"); + + await runtime.pageLoad(undefined, frameSender(0, "doc")); + await runtime.pushValueUpdate(_createMockScript(), sendData("other")); + + expect(sentTargets(sendSpy)).toEqual([]); + }); + + it("bfcache 还原时 pageShow 带上的 storageName 重新登记,同时照常广播 popupPageRestored", async () => { + const { runtime, mockGroup } = _createRuntimeContext(); + vi.spyOn(runtime, "getScriptsForTab").mockResolvedValue(scriptsFor()); + const sendSpy = vi.spyOn(chrome.tabs, "sendMessage"); + + // 跳到不运行脚本的页面后再后退 + await runtime.pageLoad(undefined, frameSender(0, "other-page")); + await runtime.pageShow({ storageNames: ["a"] }, frameSender(0, "restored")); + await runtime.pushValueUpdate(_createMockScript(), sendData("a")); + + expect(sentTargets(sendSpy)).toEqual([ + [11, "scripting/runtime/valueUpdates", ["a"], { frameId: 0, documentId: "restored" }], + ]); + expect(mockGroup.emit).toHaveBeenCalledWith("popupPageRestored", { + tabId: 11, + frameId: 0, + url: "https://www.example.com/page", + }); + }); +}); + describe("registerUserscripts 注册健康检查", () => { let runtime: RuntimeService; let originalScripting: unknown; diff --git a/src/app/service/service_worker/runtime.ts b/src/app/service/service_worker/runtime.ts index ec2ba95d6..37feb6ed9 100644 --- a/src/app/service/service_worker/runtime.ts +++ b/src/app/service/service_worker/runtime.ts @@ -32,6 +32,7 @@ import { cacheInstance } from "@App/app/cache"; import { UrlMatch } from "@App/pkg/utils/match"; import { stackAsyncTask } from "@App/pkg/utils/async_queue"; import { ExtensionContentMessageSend } from "@Packages/message/extension_message"; +import { ValueUpdateDelivery } from "./value_delivery"; import { sendMessage } from "@Packages/message/client"; import type { CompileScriptCodeResource } from "../content/utils"; import { @@ -131,11 +132,6 @@ export type TScriptsForTab = { const bgScriptStorageNames = new Set(); -// For Firefox, StorageArea.setAccessLevel is not implemented. -// See https://bugzilla.mozilla.org/show_bug.cgi?id=1724754 -// const deliveryStorage = isFirefox() ? chrome.storage.local : chrome.storage.session; -const deliveryStorage = chrome.storage.local; // 日后再处理 - export class RuntimeService { scriptMatchEnable: UrlMatch = new UrlMatch(); blackMatch: UrlMatch = new UrlMatch(); @@ -151,6 +147,7 @@ export class RuntimeService { private sorter: Record = {}; private readonly codeCacheMap = new Map(); private readonly pageLoadCaches = new Map(); + private readonly valueDelivery = new ValueUpdateDelivery(); private sandboxInitializationReplayed = false; private readonly cachedPatterns = new Map< string, @@ -477,13 +474,11 @@ export class RuntimeService { public async pushValueUpdate(script: Script, sendData: ValueUpdateDataEncoded) { try { - // 前台腳本 (推送值到tab) - await deliveryStorage!.set({ - valueUpdateDelivery: { - rId: `${Date.now()}.${Math.random()}`, // 用于区分不同的更新,确保 deliveryStorage.onChanged 必能触发 - sendData, - }, - }); + // 前台脚本:只投递给 pageLoad / pageShow 登记过运行该 storageName 的 document。 + // 不能借 chrome.storage.local 广播:每个 frame 都要为此监听 local.onChanged, + // 任何一次 local 写入(包括整包的 value:*)的新旧值都会被投递并反序列化到所有 frame(#1834)。 + // 只等待进入投递队列,不等待页面收到,避免阻塞下面的后台脚本投递 + await this.valueDelivery.push(sendData); // 後台腳本 if (bgScriptStorageNames.has(sendData.storageName)) { @@ -511,19 +506,8 @@ export class RuntimeService { } } - async setSessionAccessLevel() { - try { - // 让 scripting 存取 chrome.storage.session - await chrome.storage.session.setAccessLevel({ accessLevel: "TRUSTED_AND_UNTRUSTED_CONTEXTS" }); - } catch (e) { - this.logger.error("set session storage access level failed", Logger.E(e)); - } - } - init() { - if (deliveryStorage === chrome.storage.session) { - this.setSessionAccessLevel(); - } + this.valueDelivery.init(); // 启动gm api const permission = new PermissionVerify(this.group.group("permission"), this.mq); this.gmApi = new GMApi( @@ -1282,7 +1266,19 @@ export class RuntimeService { const tabId = chromeSender.tab?.id; const frameId = chromeSender.frameId; const incognito = chromeSender.tab?.incognito ?? false; + // 不属于任何标签页的页面无法用 tabs.sendMessage 投递,不登记 + const target = + tabId !== undefined && tabId > 0 ? { tabId, frameId: frameId ?? 0, documentId: chromeSender.documentId } : null; + // 必须在第一个 await 之前:新页面子 frame 的 pageLoad 可能先于顶层 frame 完成, + // 若等顶层查完脚本再清,就会把它们一并清掉 + if (target && !frameId) this.valueDelivery.resetTab(target.tabId); + if (target) this.valueDelivery.register(target, null); const res = await this.getScriptsForTab({ url, tabId, frameId, incognito }); + if (target) { + // 与 scripting 计算 activeStorageNames 的口径一致;没有脚本的 frame 也登记,用于「整页还是定向」的计数 + const storageNames = res ? [...res.injectScriptList, ...res.contentScriptList].map(getStorageName) : []; + this.valueDelivery.register(target, storageNames); + } // 页面可能不属于任何标签页(sender.tab 缺失或为 TAB_ID_NONE),脚本照常下发,但不能记运行计数: // 弹窗把 tabId -1 当作后台脚本的命名空间,记进去普通脚本就会混进后台脚本列表(#1774)。 @@ -1310,15 +1306,23 @@ export class RuntimeService { } /** * bfcache 还原:文档连同里面已注入的脚本被整体恢复,content script 不会重新执行, - * 因此不会再走 pageLoad。这里只重新广播一次「本页扩展触及得到」, + * 因此不会再走 pageLoad。这里重新广播一次「本页扩展触及得到」,并按 scripting 上报的 + * storageName 重新登记值更新投递(离开时已被新页面的 pageLoad 清掉)。 * 绝不能顺带重放脚本——脚本本来就还在页面里跑着。 */ - async pageShow(_: any, sender: IGetSender) { + async pageShow(params: { storageNames?: string[] } | undefined, sender: IGetSender) { const chromeSender = sender.getSender(); const url = chromeSender?.url; if (!url) return; + const tabId = chromeSender.tab?.id; + if (tabId !== undefined && tabId > 0 && params?.storageNames?.length) { + this.valueDelivery.register( + { tabId, frameId: chromeSender.frameId ?? 0, documentId: chromeSender.documentId }, + params.storageNames + ); + } this.mq.emit("popupPageRestored", { - tabId: chromeSender.tab?.id || -1, + tabId: tabId || -1, frameId: chromeSender.frameId, url, }); diff --git a/src/app/service/service_worker/value.ts b/src/app/service/service_worker/value.ts index 6f5af7ba5..be73e3f22 100644 --- a/src/app/service/service_worker/value.ts +++ b/src/app/service/service_worker/value.ts @@ -168,10 +168,14 @@ export class ValueService { valueUpdated, } as ValueUpdateDataEncoded; this.pushValueUpdate(script, sendData); + return sendData; } - setScriptValues(params: Pick, _sender: IGetSender) { - return this.setValues(params); + async setScriptValues( + params: Pick, + _sender: IGetSender + ) { + await this.setValues(params); } init(runtime: RuntimeService, popup: PopupService) { diff --git a/src/app/service/service_worker/value_delivery.test.ts b/src/app/service/service_worker/value_delivery.test.ts new file mode 100644 index 000000000..cdf55c81a --- /dev/null +++ b/src/app/service/service_worker/value_delivery.test.ts @@ -0,0 +1,383 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { cacheInstance } from "@App/app/cache"; +import type { ValueUpdateDataEncoded, ValueUpdateSender } from "../content/types"; +import { ValueUpdateDelivery } from "./value_delivery"; + +type SendCall = { tabId: number; options?: chrome.tabs.MessageSendOptions; storageNames: string[] }; + +const update = (storageName: string, sender: ValueUpdateSender = { runFlag: "", tabId: -1 }, id = storageName) => + ({ + id, + entries: [], + uuid: `uuid-${storageName}`, + storageName, + sender, + valueUpdated: true, + }) as ValueUpdateDataEncoded; + +const doc = (frameId: number) => `doc-${frameId}`; +const target = (tabId: number, frameId: number) => ({ tabId, frameId, documentId: doc(frameId) }); + +let calls: SendCall[]; +let deliver: (tabId: number, options?: chrome.tabs.MessageSendOptions) => Promise; + +beforeEach(async () => { + await cacheInstance.clear(); + calls = []; + deliver = () => Promise.resolve(undefined); + vi.spyOn(chrome.tabs, "sendMessage").mockImplementation((( + tabId: number, + msg: { action: string; data: ValueUpdateDataEncoded[] }, + options?: chrome.tabs.MessageSendOptions + ) => { + expect(msg.action).toBe("scripting/runtime/valueUpdates"); + calls.push({ tabId, options, storageNames: msg.data.map((d) => d.storageName) }); + return deliver(tabId, options); + }) as never); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +const deferred = () => { + let resolve!: () => void; + let reject!: (e: Error) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +}; + +describe("ValueUpdateDelivery 投递目标", () => { + it("只定向投递给运行了该 storageName 的 document", async () => { + const delivery = new ValueUpdateDelivery(); + delivery.register(target(1, 0), ["s1"]); + delivery.register(target(1, 5), []); + delivery.register(target(1, 6), []); + delivery.register(target(2, 0), ["s2"]); + + await delivery.push(update("s1")); + + expect(calls).toEqual([{ tabId: 1, options: { frameId: 0, documentId: "doc-0" }, storageNames: ["s1"] }]); + }); + + it("发起写入的 document 尚未登记时也会收到,保证 GM.setValue 的回执", async () => { + const delivery = new ValueUpdateDelivery(); + + await delivery.push(update("s1", { runFlag: "f", tabId: 3, frameId: 2, documentId: "early-doc" })); + + expect(calls).toEqual([{ tabId: 3, options: { frameId: 2, documentId: "early-doc" }, storageNames: ["s1"] }]); + }); + + // 子 frame 跳到新页面后、新页面 pageLoad 登记完成前,旧页面的登记还在; + // early-start 脚本此时写值,回执必须发给新页面的 document,而不是被并进同一 frameId 的旧 document + it("发起方与同一 frame 里尚未清掉的旧 document 不同时,回执发给发起方的 document", async () => { + const delivery = new ValueUpdateDelivery(); + for (let frameId = 0; frameId < 8; frameId++) delivery.register(target(1, frameId), []); + delivery.register({ tabId: 1, frameId: 5, documentId: "old-doc" }, ["s1"]); + deliver = (_, options) => + options?.documentId === "old-doc" ? Promise.reject(new Error("No document")) : Promise.resolve(undefined); + + await delivery.push(update("s1", { runFlag: "f", tabId: 1, frameId: 5, documentId: "new-doc" })); + + await vi.waitFor(() => expect(calls.map((c) => c.options?.documentId).sort()).toEqual(["new-doc", "old-doc"])); + }); + + it("发起方 document 投递失败时,不移除同一 frameId 下已登记的其他 document", async () => { + const delivery = new ValueUpdateDelivery(); + for (let frameId = 0; frameId < 8; frameId++) delivery.register(target(1, frameId), []); + delivery.register({ tabId: 1, frameId: 5, documentId: "registered" }, ["s1"]); + deliver = (_, options) => + options?.documentId === "gone" ? Promise.reject(new Error("No document")) : Promise.resolve(undefined); + + await delivery.push(update("s1", { runFlag: "f", tabId: 1, frameId: 5, documentId: "gone" }, "a")); + await vi.waitFor(() => expect(calls).toHaveLength(2)); + await delivery.push(update("s1", undefined, "b")); + + await vi.waitFor(() => expect(calls).toHaveLength(3)); + expect(calls[2].options).toEqual({ frameId: 5, documentId: "registered" }); + }); + + it("没有任何目标、发起方也不是标签页时不发送", async () => { + const delivery = new ValueUpdateDelivery(); + delivery.register(target(1, 0), ["other"]); + + await delivery.push(update("s1", { runFlag: "user", tabId: -2 })); + + expect(calls).toEqual([]); + }); + + it("缺少 documentId 时退回按 frameId 定向", async () => { + const delivery = new ValueUpdateDelivery(); + delivery.register({ tabId: 1, frameId: 4 }, ["s1"]); + + await delivery.push(update("s1")); + + expect(calls).toEqual([{ tabId: 1, options: { frameId: 4 }, storageNames: ["s1"] }]); + }); +}); + +describe("ValueUpdateDelivery 整页与定向的选择", () => { + // 单次消息的固定成本约为每多一个 frame 的两倍(Chrome 156 实测), + // 运行该脚本的 frame 超过约三分之一时,整个标签页发一次比逐个定向便宜 + const tabWith = (frameCount: number, runningCount: number) => { + const delivery = new ValueUpdateDelivery(); + for (let frameId = 0; frameId < frameCount; frameId++) { + delivery.register(target(1, frameId), frameId < runningCount ? ["s1"] : []); + } + return delivery; + }; + + it("10 个 frame 中 4 个运行时逐个定向", async () => { + const delivery = tabWith(10, 4); + + await delivery.push(update("s1")); + + expect(calls.map((c) => c.options?.frameId)).toEqual([0, 1, 2, 3]); + }); + + it("10 个 frame 中 5 个运行时整个标签页发一次", async () => { + const delivery = tabWith(10, 5); + + await delivery.push(update("s1")); + + expect(calls).toEqual([{ tabId: 1, options: undefined, storageNames: ["s1"] }]); + }); + + it("定向时每个 document 只收到自己运行的 storageName", async () => { + const delivery = new ValueUpdateDelivery(); + for (let frameId = 0; frameId < 8; frameId++) { + delivery.register(target(1, frameId), frameId === 0 ? ["s1"] : frameId === 1 ? ["s2"] : []); + } + const first = deferred(); + deliver = () => first.promise; + await delivery.push(update("s0-tab-busy", { runFlag: "", tabId: 1, frameId: 7, documentId: doc(7) })); + deliver = () => Promise.resolve(undefined); + await delivery.push(update("s1")); + await delivery.push(update("s2")); + first.resolve(); + + await vi.waitFor(() => expect(calls).toHaveLength(3)); + expect(calls.slice(1)).toEqual([ + { tabId: 1, options: { frameId: 0, documentId: "doc-0" }, storageNames: ["s1"] }, + { tabId: 1, options: { frameId: 1, documentId: "doc-1" }, storageNames: ["s2"] }, + ]); + }); +}); + +describe("ValueUpdateDelivery 合并与并发", () => { + it("同一标签页有消息在途时,后续更新按顺序合并成一条", async () => { + const delivery = new ValueUpdateDelivery(); + delivery.register(target(1, 0), ["s1"]); + const first = deferred(); + deliver = () => first.promise; + + await delivery.push(update("s1", undefined, "a")); + await delivery.push(update("s1", undefined, "b")); + await delivery.push(update("s1", undefined, "c")); + expect(calls).toHaveLength(1); + + deliver = () => Promise.resolve(undefined); + first.resolve(); + + await vi.waitFor(() => expect(calls).toHaveLength(2)); + const sent = vi + .mocked(chrome.tabs.sendMessage) + .mock.calls.map(([, msg]) => (msg as { data: ValueUpdateDataEncoded[] }).data.map((d) => d.id)); + expect(sent).toEqual([["a"], ["b", "c"]]); + }); + + it("一个标签页在途不会阻塞其他标签页", async () => { + const delivery = new ValueUpdateDelivery(); + delivery.register(target(1, 0), ["s1"]); + delivery.register(target(2, 0), ["s1"]); + const tab1 = deferred(); + deliver = (tabId) => (tabId === 1 ? tab1.promise : Promise.resolve(undefined)); + + await delivery.push(update("s1", undefined, "a")); + await delivery.push(update("s1", undefined, "b")); + + await vi.waitFor(() => expect(calls.map((c) => c.tabId)).toEqual([1, 2, 2])); + }); + + it("投递失败的 document 会被移出,不阻塞后续更新", async () => { + const delivery = new ValueUpdateDelivery(); + delivery.register(target(1, 0), ["s1"]); + delivery.register(target(1, 9), ["s1"]); + for (let frameId = 1; frameId < 8; frameId++) delivery.register(target(1, frameId), []); + deliver = (_, options) => + options?.frameId === 9 ? Promise.reject(new Error("No frame with id 9")) : Promise.resolve(undefined); + + await delivery.push(update("s1", undefined, "a")); + await vi.waitFor(() => expect(calls).toHaveLength(2)); + await delivery.push(update("s1", undefined, "b")); + + await vi.waitFor(() => expect(calls).toHaveLength(3)); + expect(calls[2].options).toEqual({ frameId: 0, documentId: "doc-0" }); + }); +}); + +// 扩展消息上限 64 MiB;超限时 Chrome 的 tabs.sendMessage 同步抛出,而不是返回被拒绝的 Promise(Chrome 156 实测)。 +// 每条更新都带新旧值,合并后的批次可能超限,而其中每一条单独发送并不超限 +describe("ValueUpdateDelivery 消息超过上限", () => { + const oversize = () => { + throw new Error("Message exceeded maximum allowed size of 64MiB."); + }; + + it("合并后的批次超限时逐条重发,队列不会卡住,document 也不被移出", async () => { + const delivery = new ValueUpdateDelivery(); + delivery.register(target(1, 0), ["s1"]); + const first = deferred(); + deliver = () => first.promise; + await delivery.push(update("s1", undefined, "a")); + await delivery.push(update("s1", undefined, "b")); + await delivery.push(update("s1", undefined, "c")); + let batches = 0; + deliver = () => (++batches === 1 ? oversize() : Promise.resolve(undefined)); + + first.resolve(); + await vi.waitFor(() => expect(calls).toHaveLength(4)); + await delivery.push(update("s1", undefined, "d")); + + await vi.waitFor(() => expect(calls).toHaveLength(5)); + const sent = vi + .mocked(chrome.tabs.sendMessage) + .mock.calls.map(([, msg]) => (msg as { data: ValueUpdateDataEncoded[] }).data.map((d) => d.id)); + expect(sent).toEqual([["a"], ["b", "c"], ["b"], ["c"], ["d"]]); + }); + + it("单条更新本身超限时跳过这一条,后续更新照常投递给同一个 document", async () => { + const delivery = new ValueUpdateDelivery(); + delivery.register(target(1, 0), ["s1"]); + vi.mocked(chrome.tabs.sendMessage).mockImplementationOnce(((tabId: number, _msg: never, options: never) => { + calls.push({ tabId, options, storageNames: ["s1"] }); + return oversize(); + }) as never); + + await delivery.push(update("s1", undefined, "huge")); + await vi.waitFor(() => expect(calls).toHaveLength(1)); + await delivery.push(update("s1", undefined, "small")); + + await vi.waitFor(() => expect(calls).toHaveLength(2)); + expect(calls[1].options).toEqual({ frameId: 0, documentId: "doc-0" }); + }); +}); + +describe("ValueUpdateDelivery 页面生命周期", () => { + it("顶层 frame 重新载入会清掉该标签页旧页面的 document,之后登记的保留", async () => { + const delivery = new ValueUpdateDelivery(); + delivery.register(target(1, 0), ["s1"]); + delivery.register(target(1, 3), ["s1"]); + + delivery.resetTab(1); + delivery.register(target(1, 8), ["s1"]); + + await delivery.push(update("s1")); + expect(calls).toEqual([{ tabId: 1, options: { frameId: 8, documentId: "doc-8" }, storageNames: ["s1"] }]); + }); + + it("关闭标签页后不再投递", async () => { + const delivery = new ValueUpdateDelivery(); + delivery.register(target(1, 0), ["s1"]); + + delivery.removeTab(1); + + await delivery.push(update("s1")); + expect(calls).toEqual([]); + }); + + it.each([ + ["关闭", () => chrome.tabs.remove(1)], + // 标签页被丢弃后重新激活等情况下,浏览器用新 tabId 替换旧的,旧 tabId 不会再触发 onRemoved + [ + "被替换", + () => (chrome.tabs as unknown as { hook: { emit: (...a: unknown[]) => void } }).hook.emit("replace", 9, 1), + ], + ])("浏览器通知标签页%s后不再向它投递", async (_label, trigger) => { + const delivery = new ValueUpdateDelivery(); + delivery.init(); + delivery.register(target(1, 0), ["s1"]); + delivery.register(target(2, 0), ["s1"]); + + trigger(); + + await delivery.push(update("s1")); + expect(calls.map((c) => c.tabId)).toEqual([2]); + }); + + it("bfcache 还原时重新登记的 document 能收到更新", async () => { + const delivery = new ValueUpdateDelivery(); + delivery.register(target(1, 0), ["s1"]); + // 跳到不运行脚本的页面 + delivery.resetTab(1); + delivery.register({ tabId: 1, frameId: 0, documentId: "other-page" }, []); + // 后退:bfcache 还原原文档,pageShow 带上它仍在运行的 storageName + delivery.register(target(1, 0), ["s1"]); + + await delivery.push(update("s1")); + expect(calls).toEqual([{ tabId: 1, options: { frameId: 0, documentId: "doc-0" }, storageNames: ["s1"] }]); + }); +}); + +describe("ValueUpdateDelivery Service Worker 重启", () => { + it("新实例从 storage.session 恢复投递目标", async () => { + const before = new ValueUpdateDelivery(); + before.register(target(1, 0), ["s1"]); + before.register(target(1, 4), []); + await before.push(update("warm-up")); + + const after = new ValueUpdateDelivery(); + await after.push(update("s1")); + + expect(calls).toEqual([{ tabId: 1, options: { frameId: 0, documentId: "doc-0" }, storageNames: ["s1"] }]); + }); + + it("恢复前已重新载入的标签页不会混入旧页面的 document,其他 frame 的登记会合并", async () => { + const before = new ValueUpdateDelivery(); + before.register(target(1, 0), ["s1"]); + before.register(target(2, 0), ["s1"]); + await before.push(update("warm-up")); + + const after = new ValueUpdateDelivery(); + after.resetTab(1); + after.register(target(2, 7), ["s1"]); + // 标签页 2 的 frame 足够多,才能从定向投递里看出恢复出的 frame 0 与新登记的 frame 7 都在 + for (let frameId = 1; frameId < 6; frameId++) after.register(target(2, frameId), []); + await after.push(update("s1")); + + expect(calls.map((c) => [c.tabId, c.options?.frameId])).toEqual([ + [2, 7], + [2, 0], + ]); + }); + + // 广告等 iframe 反复载入时,没有脚本的 frame 只用于「整页还是定向」的计数,不值得每次都重写一遍持久化记录 + it("只持久化运行脚本的 frame,没有脚本的 frame 登记不写 storage.session", async () => { + const delivery = new ValueUpdateDelivery(); + delivery.register(target(1, 0), ["s1"]); + await delivery.push(update("warm-up")); + const setSpy = vi.spyOn(chrome.storage.session, "set"); + + for (let frameId = 1; frameId <= 3; frameId++) delivery.register(target(1, frameId), []); + await delivery.push(update("warm-up")); + + expect(setSpy).not.toHaveBeenCalled(); + expect(await chrome.storage.session.get(null)).toEqual({ + "valueUpdateTargets:1": { 0: { documentId: "doc-0", storageNames: ["s1"] } }, + }); + }); + + it("关闭的标签页也从 storage.session 移除", async () => { + const before = new ValueUpdateDelivery(); + before.register(target(1, 0), ["s1"]); + before.removeTab(1); + await before.push(update("warm-up")); + + const after = new ValueUpdateDelivery(); + await after.push(update("s1")); + + expect(calls).toEqual([]); + }); +}); diff --git a/src/app/service/service_worker/value_delivery.ts b/src/app/service/service_worker/value_delivery.ts new file mode 100644 index 000000000..2653db638 --- /dev/null +++ b/src/app/service/service_worker/value_delivery.ts @@ -0,0 +1,269 @@ +import LoggerCore from "@App/app/logger/core"; +import Logger from "@App/app/logger/logger"; +import { cacheInstance } from "@App/app/cache"; +import { CACHE_KEY_VALUE_UPDATE_TARGETS } from "@App/app/cache_key"; +import { ExtensionContentMessageSend } from "@Packages/message/extension_message"; +import type { ValueUpdateDataEncoded } from "../content/types"; + +export type ValueUpdateTarget = { tabId: number; frameId: number; documentId?: string }; + +// storageNames 为 null:pageLoad 已到达但还没查出运行哪些脚本(early-start 脚本此时已在运行),所有更新都投递, +// 与 scripting 在 pageLoad 返回前两侧都转发的语义一致 +type FrameRecord = { documentId?: string; storageNames: string[] | null }; +const runs = (frame: FrameRecord, storageName: string) => + frame.storageNames === null || frame.storageNames.includes(storageName); +// 持久化形状:frameId → 该 frame 当前 document 运行的 storageName +type PersistedTab = Record; + +type Route = { frameId: number; documentId?: string; items: ValueUpdateDataEncoded[] }; + +const ACTION = "scripting/runtime/valueUpdates"; + +/** + * 把值更新推送给页面里运行该 storageName 的 frame。 + * + * 投递表的真相在 storage.session,内存里只是副本:SW 被回收后首次使用时恢复,不依赖任何长连接。 + * 同一标签页同时只有一批消息在途,期间到来的更新攒成下一批,高频写入时消息数随标签页数而非写入次数增长; + * 不同标签页之间互不等待。 + */ +export class ValueUpdateDelivery { + private readonly logger = LoggerCore.logger({ component: "valueUpdateDelivery" }); + private readonly tabs = new Map>(); + private readonly persistedTabs = new Set(); + // 恢复完成前就重新载入或关闭的标签页,持久化里的旧记录不能再合并回来 + private readonly droppedBeforeRestore = new Set(); + private restoring: Promise | null = null; + private restored = false; + private readonly queues = new Map(); + + init() { + chrome.tabs.onRemoved.addListener((tabId) => { + const lastError = chrome.runtime.lastError; + if (lastError) { + console.error("chrome.runtime.lastError in chrome.tabs.onRemoved:", lastError); + return; + } + this.removeTab(tabId); + }); + // 标签页被丢弃等情况下浏览器会用新 tabId 替换原标签页,旧 tabId 不会再触发 onRemoved + chrome.tabs.onReplaced.addListener((_addedTabId, removedTabId) => { + const lastError = chrome.runtime.lastError; + if (lastError) { + console.error("chrome.runtime.lastError in chrome.tabs.onReplaced:", lastError); + return; + } + this.removeTab(removedTabId); + }); + } + + register(target: ValueUpdateTarget, storageNames: string[] | null) { + let frames = this.tabs.get(target.tabId); + if (!frames) { + frames = new Map(); + this.tabs.set(target.tabId, frames); + } + const previous = frames.get(target.frameId); + frames.set(target.frameId, { documentId: target.documentId, storageNames }); + if (storageNames?.length || previous?.storageNames?.length) this.persist(target.tabId); + } + + /** + * 顶层 frame 开始载入新页面:旧页面的 document 都已不在。 + * 必须在 pageLoad 到达时同步调用,之后才到达的子 frame 登记才不会被一并清掉。 + */ + resetTab(tabId: number) { + this.dropTab(tabId); + } + + removeTab(tabId: number) { + this.dropTab(tabId); + this.queues.delete(tabId); + } + + async push(data: ValueUpdateDataEncoded) { + await this.restore(); + const tabIds = new Set(); + for (const [tabId, frames] of this.tabs) { + for (const frame of frames.values()) { + if (runs(frame, data.storageName)) { + tabIds.add(tabId); + break; + } + } + } + const senderTabId = data.sender.tabId; + if (senderTabId !== undefined && senderTabId > 0) tabIds.add(senderTabId); + for (const tabId of tabIds) { + const queue = this.queues.get(tabId); + if (queue) { + queue.push(data); + } else { + const created: ValueUpdateDataEncoded[] = []; + this.queues.set(tabId, created); + this.flush(tabId, created, [data]); + } + } + } + + private async flush(tabId: number, queue: ValueUpdateDataEncoded[], batch: ValueUpdateDataEncoded[]) { + for (;;) { + await this.sendBatch(tabId, batch); + // 期间标签页已关闭 + if (this.queues.get(tabId) !== queue) return; + if (!queue.length) { + this.queues.delete(tabId); + return; + } + batch = queue.splice(0); + } + } + + private sendBatch(tabId: number, batch: ValueUpdateDataEncoded[]) { + const frames = this.tabs.get(tabId) ?? new Map(); + // 按 document 区分路由:同一 frameId 下,尚未被新页面 pageLoad 替换的旧 document 与发起写入的新 document 要分开投递 + const routes = new Map(); + const addRoute = (frameId: number, documentId: string | undefined, item: ValueUpdateDataEncoded) => { + const key = documentId ?? `frame:${frameId}`; + let route = routes.get(key); + if (!route) { + route = { frameId, documentId, items: [] }; + routes.set(key, route); + } + if (route.items[route.items.length - 1] !== item) route.items.push(item); + }; + for (const item of batch) { + for (const [frameId, frame] of frames) { + if (runs(frame, item.storageName)) addRoute(frameId, frame.documentId, item); + } + const { sender } = item; + if (sender.tabId === tabId && sender.frameId !== undefined) { + addRoute(sender.frameId, sender.documentId, item); + } + } + if (routes.size === 0) return Promise.resolve(); + + // 单次消息的固定成本约是整页投递里每多一个 frame 的两倍(Chrome 156 实测): + // 要投递的 frame 超过约三分之一时,整个标签页发一次(各 frame 的 scripting 再按 storageName 过滤)更便宜 + const frameCount = Math.max(frames.size, routes.size); + if (routes.size * 3 > frameCount + 2) { + const items = batch.filter((item) => [...routes.values()].some((route) => route.items.includes(item))); + return this.deliver(tabId, items).then((reached) => { + // 整页都收不到:标签页里已没有存活的 scripting(如被丢弃),等它重新载入时再登记 + if (!reached) this.dropFrames(tabId, frames); + }); + } + return Promise.all( + [...routes.values()].map((route) => + this.deliver(tabId, route.items, route).then((reached) => { + // document 已销毁(子 frame 被移除、页面已跳走) + if (!reached) this.dropFrames(tabId, frames, route); + }) + ) + ).then(() => undefined); + } + + /** + * 返回目标是否还在。tabs.sendMessage 的两类失败要分开处理: + * 同步抛出是调用本身被拒(实测为消息超过 64 MiB 上限),目标仍在,不能移出; + * 返回的 Promise 被拒绝才是目标已不存在。 + */ + private async deliver(tabId: number, items: ValueUpdateDataEncoded[], route?: Route): Promise { + let sent: Promise; + try { + sent = this.send(tabId, items, route); + } catch (e) { + // 合并后的批次超限时逐条按顺序重发;单条本身就超限则只能放弃这一条 + if (items.length > 1) { + for (const item of items) { + if (!(await this.deliver(tabId, [item], route))) return false; + } + return true; + } + this.logger.error( + "value update rejected by tabs.sendMessage", + { tabId, frameId: route?.frameId, storageName: items[0].storageName }, + Logger.E(e) + ); + return true; + } + return sent.then( + () => true, + (e) => { + this.logger.debug("value update target unreachable", { tabId, frameId: route?.frameId }, Logger.E(e)); + return false; + } + ); + } + + private send(tabId: number, items: ValueUpdateDataEncoded[], route?: Route) { + const options = route + ? route.documentId === undefined + ? { frameId: route.frameId } + : { frameId: route.frameId, documentId: route.documentId } + : undefined; + return new ExtensionContentMessageSend(tabId, options).notify({ action: ACTION, data: items }); + } + + // 只移除发送时看到、且属于收不到的那个 document 的记录:期间若同一 frame 已重新登记,新记录保留; + // 发起方的 document 尚未登记时投递失败,也不能连带移除同一 frameId 下的其他 document。不传 route 表示整页都收不到 + private dropFrames(tabId: number, snapshot: Map, route?: Route) { + const frames = this.tabs.get(tabId); + if (!frames) return; + for (const frameId of route ? [route.frameId] : [...snapshot.keys()]) { + const record = snapshot.get(frameId); + if (!record || frames.get(frameId) !== record) continue; + if (route && route.documentId !== undefined && record.documentId !== route.documentId) continue; + frames.delete(frameId); + } + if (frames.size === 0) this.tabs.delete(tabId); + this.persist(tabId); + } + + private dropTab(tabId: number) { + this.tabs.delete(tabId); + if (!this.restored) this.droppedBeforeRestore.add(tabId); + this.persist(tabId); + } + + private restore() { + this.restoring ??= this.load(); + return this.restoring; + } + + private async load() { + const keys = (await cacheInstance.list()).filter((key) => key.startsWith(CACHE_KEY_VALUE_UPDATE_TARGETS)); + const records = await Promise.all(keys.map((key) => cacheInstance.get(key))); + keys.forEach((key, i) => { + const tabId = Number(key.slice(CACHE_KEY_VALUE_UPDATE_TARGETS.length)); + this.persistedTabs.add(tabId); + const record = records[i]; + if (!record || this.droppedBeforeRestore.has(tabId)) return; + let frames = this.tabs.get(tabId); + if (!frames) { + frames = new Map(); + this.tabs.set(tabId, frames); + } + for (const [frameId, frame] of Object.entries(record)) { + // 恢复前已到达的登记更新 + if (!frames.has(Number(frameId))) frames.set(Number(frameId), frame); + } + }); + this.droppedBeforeRestore.clear(); + this.restored = true; + } + + // 在恢复之后写入:恢复前写会用不完整的内存副本覆盖持久化记录。 + // 只落盘运行脚本的 frame:没有脚本的 frame(如反复载入的广告 iframe)只参与「整页还是定向」的计数, + // SW 重启后少计它们只会让选择偏向整页投递,结果仍然正确 + private persist(tabId: number) { + this.restore().then(() => { + const running = [...(this.tabs.get(tabId) ?? [])].filter(([, frame]) => !!frame.storageNames?.length); + const key = `${CACHE_KEY_VALUE_UPDATE_TARGETS}${tabId}`; + if (running.length) { + this.persistedTabs.add(tabId); + return cacheInstance.set(key, Object.fromEntries(running)); + } + if (this.persistedTabs.delete(tabId)) return cacheInstance.del(key); + }); + } +}