This commit is contained in:
IndieKKY
2024-10-06 11:51:40 +08:00
parent fde80103d9
commit d7b274d338
5 changed files with 16 additions and 19 deletions

View File

@@ -101,9 +101,6 @@ class ExtensionMessage {
const portContext: PortContext = {id, name, port, portMessageHandler, ready: false} const portContext: PortContext = {id, name, port, portMessageHandler, ready: false}
this.portIdToPort.set(id, portContext) this.portIdToPort.set(id, portContext)
// 开始监听
portMessageHandler.startListen()
// 监听断开连接 // 监听断开连接
port.onDisconnect.addListener(() => { port.onDisconnect.addListener(() => {
this.portIdToPort.delete(id) this.portIdToPort.delete(id)

View File

@@ -69,8 +69,7 @@ class InjectMessage {
name: MESSAGE_TARGET_INJECT, name: MESSAGE_TARGET_INJECT,
}) })
this.portMessageHandler = new Layer1Protocol<MessageData, MessageResult>(this.messageHandler, this.port) this.portMessageHandler = new Layer1Protocol<MessageData, MessageResult>(this.messageHandler, this.port)
this.portMessageHandler!.startListen() this.portMessageHandler.sendMessage({
this.portMessageHandler!.sendMessage({
method: '_init', method: '_init',
params: { params: {
type: 'inject', type: 'inject',

View File

@@ -20,17 +20,24 @@ type RespMsg<T = any> = {
class Layer1Protocol<L1Req = any, L1Res = any> { class Layer1Protocol<L1Req = any, L1Res = any> {
private port: chrome.runtime.Port private port: chrome.runtime.Port
private timeout: number private timeout: number
private messageMap: Map<string, { resolve: (value: L1Res) => void, timer: number }> private requests: Map<string, { resolve: (value: L1Res) => void, timer: number }>
private handler: (value: L1Req) => Promise<L1Res> private handler: (value: L1Req) => Promise<L1Res>
constructor(handler: (value: L1Req) => Promise<L1Res>, port: chrome.runtime.Port, timeout = 30000) { // 默认超时 30 秒 constructor(handler: (value: L1Req) => Promise<L1Res>, port: chrome.runtime.Port, timeout = 30000) { // 默认超时 30 秒
this.port = port; this.port = port;
this.timeout = timeout; this.timeout = timeout;
this.messageMap = new Map(); this.requests = new Map();
this.handler = handler this.handler = handler
this._startListen()
} }
startListen() { // 生成唯一 ID简单示例可以使用更复杂的生成策略
_generateUniqueId() {
return crypto.randomUUID()
}
_startListen() {
// 持久监听 port.onMessage // 持久监听 port.onMessage
this.port.onMessage.addListener((msg: ReqMsg<L1Req, L1Res>) => { this.port.onMessage.addListener((msg: ReqMsg<L1Req, L1Res>) => {
const { id, type, req, res } = msg; const { id, type, req, res } = msg;
@@ -50,12 +57,12 @@ class Layer1Protocol<L1Req = any, L1Res = any> {
this.port.postMessage({ id, type: 'res', res: response }); this.port.postMessage({ id, type: 'res', res: response });
}); });
} else if (type === 'res') { } else if (type === 'res') {
if (this.messageMap.has(id)) { if (this.requests.has(id)) {
const { resolve, timer } = this.messageMap.get(id)!; const { resolve, timer } = this.requests.get(id)!;
// 清除超时定时器 // 清除超时定时器
clearTimeout(timer); clearTimeout(timer);
// 移除消息 ID // 移除消息 ID
this.messageMap.delete(id); this.requests.delete(id);
// 通过 ID 找到对应的 Promise 并 resolve // 通过 ID 找到对应的 Promise 并 resolve
resolve(res!.data!); resolve(res!.data!);
}else { }else {
@@ -75,22 +82,17 @@ class Layer1Protocol<L1Req = any, L1Res = any> {
// 设置一个超时定时器 // 设置一个超时定时器
const timer = setTimeout(() => { const timer = setTimeout(() => {
// 超时后执行 reject 并从 Map 中删除 // 超时后执行 reject 并从 Map 中删除
this.messageMap.delete(id); this.requests.delete(id);
reject(new Error(`Request timed out after ${this.timeout / 1000} seconds`)); reject(new Error(`Request timed out after ${this.timeout / 1000} seconds`));
}, this.timeout); }, this.timeout);
// 将 resolve 和 timer 函数与消息 ID 绑定,存入 Map // 将 resolve 和 timer 函数与消息 ID 绑定,存入 Map
this.messageMap.set(id, { resolve, timer }); this.requests.set(id, { resolve, timer });
// 发送消息,并附带 ID // 发送消息,并附带 ID
this.port.postMessage({ id, type: 'req', req }); this.port.postMessage({ id, type: 'req', req });
}); });
} }
// 生成唯一 ID简单示例可以使用更复杂的生成策略
_generateUniqueId() {
return crypto.randomUUID()
}
} }
export default Layer1Protocol export default Layer1Protocol

0
src/messaging/const.ts Normal file
View File

View File

@@ -77,7 +77,6 @@ const useMessageService = (methods?: {
if (messageHandler && port) { if (messageHandler && port) {
const pmh = new Layer1Protocol<MessageData, MessageResult>(messageHandler, port) const pmh = new Layer1Protocol<MessageData, MessageResult>(messageHandler, port)
pmh.startListen()
//get tabId from url params //get tabId from url params
let tabIdStr = window.location.search.split('tabId=')[1] let tabIdStr = window.location.search.split('tabId=')[1]
let tabId = tabIdStr ? parseInt(tabIdStr) : undefined let tabId = tabIdStr ? parseInt(tabIdStr) : undefined