Skip to content

Commit 56e2c7a

Browse files
authored
refactor(ConnectionHub): fix missing connection id issue (#3180)
1 parent 8da7201 commit 56e2c7a

File tree

1 file changed

+25
-11
lines changed
  • src/BootstrapBlazor/wwwroot/modules

1 file changed

+25
-11
lines changed

src/BootstrapBlazor/wwwroot/modules/hub.js

+25-11
Original file line numberDiff line numberDiff line change
@@ -4,35 +4,46 @@ import EventHandler from "./event-handler.js?v=$version";
44

55
export async function init(id, options) {
66
const { invoke, method, interval = 3000, url, connectionId } = options;
7-
const hubs = [];
8-
const chanel = new BroadcastChannel('bb_hubs_chanel');
97
const localStorageKey = 'bb_hub_el_id';
10-
const localStorageConnectionIdKey = 'bb_hub_connection_id';
118
if (localStorage.getItem(localStorageKey) === null) {
129
localStorage.setItem(localStorageKey, id);
1310
}
1411

12+
const localStorageConnectionIdKey = 'bb_hub_connection_id';
1513
let clientId = localStorage.getItem(localStorageConnectionIdKey);
1614
if (clientId === null) {
1715
localStorage.setItem(localStorageConnectionIdKey, connectionId);
1816
clientId = connectionId;
1917
}
2018
window.addEventListener('unload', () => {
21-
chanel.close();
22-
localStorage.removeItem(localStorageKey);
19+
dispose(id);
2320
});
2421

22+
const hubs = [];
23+
const chanel = new BroadcastChannel('bb_hubs_chanel');
2524
EventHandler.on(chanel, 'message', e => {
26-
const id = e.data;
27-
if (hubs.find(v => v === id) === void 0) {
25+
const { id, type } = e.data;
26+
if (type === 'ping' && hubs.find(v => v === id) === void 0) {
2827
hubs.push(id);
2928
}
29+
else if (type === 'dispose') {
30+
const index = hubs.indexOf(v => v === id);
31+
if (index > -1) {
32+
hubs.splice(index, 1);
33+
}
34+
if (clientId === connectionId) {
35+
localStorage.removeItem(localStorageConnectionIdKey);
36+
}
37+
if (localStorage.getItem(localStorageKey) === id) {
38+
localStorage.removeItem(localStorageKey);
39+
}
40+
}
3041
});
3142

3243
const info = await getClientInfo(url);
3344
info.id = clientId;
3445
const handler = setInterval(async () => {
35-
chanel.postMessage(id);
46+
chanel.postMessage({ id, type: 'ping' });
3647
let hubId = localStorage.getItem(localStorageKey);
3748

3849
if (hubId === null) {
@@ -48,18 +59,21 @@ export async function init(id, options) {
4859
localStorage.removeItem(localStorageKey);
4960
}
5061
}
62+
else {
63+
localStorage.removeItem(localStorageKey);
64+
}
5165
}, interval);
5266

53-
const hub = { handler, chanel };
67+
const hub = { handler, chanel, connectionId };
5468
Data.set(id, hub);
5569
}
5670

5771
export async function dispose(id) {
5872
const hub = Data.get(id);
5973

6074
if (hub) {
61-
hub.chanel.close();
6275
clearInterval(hub.handler);
63-
localStorage.removeItem('bootstrapblazor_hub_id');
76+
hub.chanel.postMessage({ id, type: 'dispose' });
77+
hub.chanel.close();
6478
}
6579
}

0 commit comments

Comments
 (0)