From 56e2c7a38d1296106671c8bf49df67843084ff3d Mon Sep 17 00:00:00 2001 From: Argo Zhang Date: Sat, 30 Mar 2024 23:17:37 +0800 Subject: [PATCH] refactor(ConnectionHub): fix missing connection id issue (#3180) --- src/BootstrapBlazor/wwwroot/modules/hub.js | 36 +++++++++++++++------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/src/BootstrapBlazor/wwwroot/modules/hub.js b/src/BootstrapBlazor/wwwroot/modules/hub.js index 1b985087a89..4881b3f95dc 100644 --- a/src/BootstrapBlazor/wwwroot/modules/hub.js +++ b/src/BootstrapBlazor/wwwroot/modules/hub.js @@ -4,35 +4,46 @@ import EventHandler from "./event-handler.js?v=$version"; export async function init(id, options) { const { invoke, method, interval = 3000, url, connectionId } = options; - const hubs = []; - const chanel = new BroadcastChannel('bb_hubs_chanel'); const localStorageKey = 'bb_hub_el_id'; - const localStorageConnectionIdKey = 'bb_hub_connection_id'; if (localStorage.getItem(localStorageKey) === null) { localStorage.setItem(localStorageKey, id); } + const localStorageConnectionIdKey = 'bb_hub_connection_id'; let clientId = localStorage.getItem(localStorageConnectionIdKey); if (clientId === null) { localStorage.setItem(localStorageConnectionIdKey, connectionId); clientId = connectionId; } window.addEventListener('unload', () => { - chanel.close(); - localStorage.removeItem(localStorageKey); + dispose(id); }); + const hubs = []; + const chanel = new BroadcastChannel('bb_hubs_chanel'); EventHandler.on(chanel, 'message', e => { - const id = e.data; - if (hubs.find(v => v === id) === void 0) { + const { id, type } = e.data; + if (type === 'ping' && hubs.find(v => v === id) === void 0) { hubs.push(id); } + else if (type === 'dispose') { + const index = hubs.indexOf(v => v === id); + if (index > -1) { + hubs.splice(index, 1); + } + if (clientId === connectionId) { + localStorage.removeItem(localStorageConnectionIdKey); + } + if (localStorage.getItem(localStorageKey) === id) { + localStorage.removeItem(localStorageKey); + } + } }); const info = await getClientInfo(url); info.id = clientId; const handler = setInterval(async () => { - chanel.postMessage(id); + chanel.postMessage({ id, type: 'ping' }); let hubId = localStorage.getItem(localStorageKey); if (hubId === null) { @@ -48,9 +59,12 @@ export async function init(id, options) { localStorage.removeItem(localStorageKey); } } + else { + localStorage.removeItem(localStorageKey); + } }, interval); - const hub = { handler, chanel }; + const hub = { handler, chanel, connectionId }; Data.set(id, hub); } @@ -58,8 +72,8 @@ export async function dispose(id) { const hub = Data.get(id); if (hub) { - hub.chanel.close(); clearInterval(hub.handler); - localStorage.removeItem('bootstrapblazor_hub_id'); + hub.chanel.postMessage({ id, type: 'dispose' }); + hub.chanel.close(); } }