From b91e1476d6bfbe8ce8901bb8b55ffdfc0e7c1644 Mon Sep 17 00:00:00 2001 From: IndieKKY Date: Sun, 6 Oct 2024 12:10:21 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/messaging/ExtensionMessage.ts | 2 +- src/messaging/Layer1Protocol.ts | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/messaging/ExtensionMessage.ts b/src/messaging/ExtensionMessage.ts index d28af84..a9ae039 100644 --- a/src/messaging/ExtensionMessage.ts +++ b/src/messaging/ExtensionMessage.ts @@ -103,8 +103,8 @@ class ExtensionMessage { // 监听断开连接 port.onDisconnect.addListener(() => { - this.portIdToPort.delete(id) this.debug('onDisconnect', id) + this.portIdToPort.delete(id) }) }) } diff --git a/src/messaging/Layer1Protocol.ts b/src/messaging/Layer1Protocol.ts index 769006a..8c8cb5d 100644 --- a/src/messaging/Layer1Protocol.ts +++ b/src/messaging/Layer1Protocol.ts @@ -26,7 +26,7 @@ class Layer1Protocol { private requests: Map void, reject: (reason?: any) => void, timer: number }> private handler: Handler - constructor(handler: Handler, port: chrome.runtime.Port, timeout = 30000) { // 默认超时 30 秒 + constructor(handler: Handler, port: chrome.runtime.Port, autoDispose = true, timeout = 30000) { // 默认超时 30 秒 this.port = port; this.timeout = timeout; this.requests = new Map(); @@ -34,6 +34,9 @@ class Layer1Protocol { // 开始监听 this.port.onMessage.addListener(this._messageListener); + if (autoDispose) { + this.port.onDisconnect.addListener(this.dispose); + } } // 生成唯一 ID(简单示例,可以使用更复杂的生成策略) @@ -80,6 +83,9 @@ class Layer1Protocol { dispose() { this.port.onMessage.removeListener(this._messageListener); + if (this.port.onDisconnect) { + this.port.onDisconnect.removeListener(this.dispose); + } this.requests.forEach(({ timer }) => clearTimeout(timer)); this.requests.clear(); }