()
| 50 | } |
| 51 | |
| 52 | init() { |
| 53 | this.extServer.on("runtime/emitEvent", (data) => { |
| 54 | // 转发给inject和content |
| 55 | return this.broadcastToPage("runtime/emitEvent", data); |
| 56 | }); |
| 57 | this.extServer.on("runtime/valueUpdate", (data) => { |
| 58 | // 转发给inject和content |
| 59 | return this.broadcastToPage("runtime/valueUpdate", data); |
| 60 | }); |
| 61 | this.server.on("logger", (data: Logger) => { |
| 62 | LoggerCore.logger().log(data.level, data.message, data.label); |
| 63 | }); |
| 64 | |
| 65 | // ================================ |
| 66 | // 来自 service_worker 的投递:storage 广播(类似 UDP) |
| 67 | // ================================ |
| 68 | |
| 69 | // 接收 service_worker 的 chrome.storage.local 值改变通知 (一对多广播) |
| 70 | // 类似 UDP 原理,service_worker 不会有任何「等待处理」 |
| 71 | // 由于 changes 会包括新旧值 (Chrome: JSON serialization, Firefox: Structured Clone) |
| 72 | // 因此需要注意资讯量不要过大导致 onChanged 的触发过慢 |
| 73 | deliveryStorage.onChanged.addListener((changes) => { |
| 74 | const record = changes["valueUpdateDelivery"]; |
| 75 | if (record?.newValue) { |
| 76 | const sendData = record.newValue.sendData as ValueUpdateDataEncoded; |
| 77 | const activeOn = |
| 78 | this.activeStorageNames === null |
| 79 | ? PageOrContent.PAGE_AND_CONTENT |
| 80 | : this.activeStorageNames.get(sendData.storageName); |
| 81 | if (activeOn) { |
| 82 | // 转发给 content 和 inject |
| 83 | this.broadcastToPage("runtime/valueUpdate", sendData, activeOn); |
| 84 | } |
| 85 | } |
| 86 | }); |
| 87 | |
| 88 | forwardMessage("serviceWorker", "script/isInstalled", this.server, this.senderToExt); |
| 89 | forwardMessage( |
| 90 | "serviceWorker", |
| 91 | "runtime/gmApi", |
| 92 | this.server, |
| 93 | this.senderToExt, |
| 94 | (data: { api: string; params: any; uuid: string }) => { |
| 95 | // 拦截关注的 API,未命中则返回 false 交由默认转发处理 |
| 96 | switch (data.api) { |
| 97 | case "CAT_createBlobUrl": { |
| 98 | const file = data.params[0] as File; |
| 99 | const url = makeBlobURL({ blob: file, persistence: false }) as string; |
| 100 | return url; |
| 101 | } |
| 102 | case "CAT_fetchBlob": { |
| 103 | return fetch(data.params[0]).then((res) => res.blob()); |
| 104 | } |
| 105 | case "CAT_agentOPFS": { |
| 106 | // chrome.runtime 不支持 Blob,write 操作的 Blob content 需先转为 blob URL |
| 107 | const req = data.params[0]; |
| 108 | if (req?.action === "write" && req.content instanceof Blob) { |
| 109 | req.content = makeBlobURL({ blob: req.content, persistence: true }) as string; |
nothing calls this directly
no test coverage detected