@@ -4,35 +4,46 @@ import EventHandler from "./event-handler.js?v=$version";
4
4
5
5
export async function init ( id , options ) {
6
6
const { invoke, method, interval = 3000 , url, connectionId } = options ;
7
- const hubs = [ ] ;
8
- const chanel = new BroadcastChannel ( 'bb_hubs_chanel' ) ;
9
7
const localStorageKey = 'bb_hub_el_id' ;
10
- const localStorageConnectionIdKey = 'bb_hub_connection_id' ;
11
8
if ( localStorage . getItem ( localStorageKey ) === null ) {
12
9
localStorage . setItem ( localStorageKey , id ) ;
13
10
}
14
11
12
+ const localStorageConnectionIdKey = 'bb_hub_connection_id' ;
15
13
let clientId = localStorage . getItem ( localStorageConnectionIdKey ) ;
16
14
if ( clientId === null ) {
17
15
localStorage . setItem ( localStorageConnectionIdKey , connectionId ) ;
18
16
clientId = connectionId ;
19
17
}
20
18
window . addEventListener ( 'unload' , ( ) => {
21
- chanel . close ( ) ;
22
- localStorage . removeItem ( localStorageKey ) ;
19
+ dispose ( id ) ;
23
20
} ) ;
24
21
22
+ const hubs = [ ] ;
23
+ const chanel = new BroadcastChannel ( 'bb_hubs_chanel' ) ;
25
24
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 ) {
28
27
hubs . push ( id ) ;
29
28
}
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
+ }
30
41
} ) ;
31
42
32
43
const info = await getClientInfo ( url ) ;
33
44
info . id = clientId ;
34
45
const handler = setInterval ( async ( ) => {
35
- chanel . postMessage ( id ) ;
46
+ chanel . postMessage ( { id , type : 'ping' } ) ;
36
47
let hubId = localStorage . getItem ( localStorageKey ) ;
37
48
38
49
if ( hubId === null ) {
@@ -48,18 +59,21 @@ export async function init(id, options) {
48
59
localStorage . removeItem ( localStorageKey ) ;
49
60
}
50
61
}
62
+ else {
63
+ localStorage . removeItem ( localStorageKey ) ;
64
+ }
51
65
} , interval ) ;
52
66
53
- const hub = { handler, chanel } ;
67
+ const hub = { handler, chanel, connectionId } ;
54
68
Data . set ( id , hub ) ;
55
69
}
56
70
57
71
export async function dispose ( id ) {
58
72
const hub = Data . get ( id ) ;
59
73
60
74
if ( hub ) {
61
- hub . chanel . close ( ) ;
62
75
clearInterval ( hub . handler ) ;
63
- localStorage . removeItem ( 'bootstrapblazor_hub_id' ) ;
76
+ hub . chanel . postMessage ( { id, type : 'dispose' } ) ;
77
+ hub . chanel . close ( ) ;
64
78
}
65
79
}
0 commit comments