@@ -23,7 +23,7 @@ export class MultichainSDK extends MultichainCore {
2323 private __provider : MultichainApiClient < RPCAPI > | undefined = undefined ;
2424 private __transport : ExtendedTransport | undefined = undefined ;
2525 private __dappClient : DappClient | undefined = undefined ;
26-
26+ private __beforeUnloadListener : ( ( ) => void ) | undefined ;
2727 public __state : SDKState = 'pending' ;
2828 private listener : ( ( ) => void | Promise < void > ) | undefined ;
2929
@@ -241,7 +241,26 @@ export class MultichainSDK extends MultichainCore {
241241 }
242242 }
243243
244+ private async onBeforeUnload ( ) {
245+ if ( this . options . ui . factory . modal ) {
246+ //Modal is still visible, remove storage to prevent glitch with "connecting" state
247+ await this . storage . removeTransport ( ) ;
248+ }
249+ }
250+
251+ private createBeforeUnloadListener ( ) {
252+ if ( typeof window !== 'undefined' ) {
253+ window . addEventListener ( 'beforeunload' , this . onBeforeUnload . bind ( this ) ) ;
254+ }
255+ return ( ) => {
256+ if ( typeof window !== 'undefined' ) {
257+ window . removeEventListener ( 'beforeunload' , this . onBeforeUnload . bind ( this ) ) ;
258+ }
259+ } ;
260+ }
244261 private async showInstallModal ( desktopPreferred : boolean , scopes : Scope [ ] , caipAccountIds : CaipAccountId [ ] ) {
262+ // create the listener only once to avoid memory leaks
263+ this . __beforeUnloadListener ??= this . createBeforeUnloadListener ( ) ;
245264 return new Promise < void > ( ( resolve , reject ) => {
246265 // Use Connection Modal
247266 this . options . ui . factory . renderInstallModal (
@@ -412,6 +431,7 @@ export class MultichainSDK extends MultichainCore {
412431
413432 async disconnect ( ) : Promise < void > {
414433 this . listener ?.( ) ;
434+ this . __beforeUnloadListener ?.( ) ;
415435
416436 await this . __transport ?. disconnect ( ) ;
417437 await this . storage . removeTransport ( ) ;
@@ -420,6 +440,7 @@ export class MultichainSDK extends MultichainCore {
420440 this . emit ( 'stateChanged' , 'disconnected' ) ;
421441
422442 this . listener = undefined ;
443+ this . __beforeUnloadListener = undefined ;
423444 this . __transport = undefined ;
424445 this . __provider = undefined ;
425446 this . __dappClient = undefined ;
0 commit comments