@@ -6,6 +6,9 @@ import { CreateContextOptions } from './types';
66import { ELECTRON_TRPC_CHANNEL } from '../constants' ;
77import { ETRPCRequest } from '../types' ;
88import { Unsubscribable } from '@trpc/server/observable' ;
9+ import debugFactory from 'debug' ;
10+
11+ const debug = debugFactory ( 'electron-trpc:main:IPCHandler' ) ;
912
1013type Awaitable < T > = T | Promise < T > ;
1114
@@ -46,23 +49,49 @@ class IPCHandler<TRouter extends AnyRouter> {
4649 return ;
4750 }
4851
52+ debug ( 'Attaching window' , win . id ) ;
53+
4954 this . #windows. push ( win ) ;
50- this . #attachSubscriptionCleanupHandler ( win ) ;
55+ this . #attachSubscriptionCleanupHandlers ( win ) ;
5156 }
5257
5358 detachWindow ( win : BrowserWindow ) {
59+ debug ( 'Detaching window' , win . id ) ;
60+
5461 this . #windows = this . #windows. filter ( ( w ) => w !== win ) ;
62+ this . #cleanUpSubscriptions( { webContentsId : win . webContents . id } ) ;
63+ }
5564
65+ #cleanUpSubscriptions( {
66+ webContentsId,
67+ frameRoutingId,
68+ } : {
69+ webContentsId : number ;
70+ frameRoutingId ?: number ;
71+ } ) {
5672 for ( const [ key , sub ] of this . #subscriptions. entries ( ) ) {
57- if ( key . startsWith ( `${ win . webContents . id } -` ) ) {
73+ if ( key . startsWith ( `${ webContentsId } -${ frameRoutingId ?? '' } ` ) ) {
74+ debug ( 'Closing subscription' , key ) ;
5875 sub . unsubscribe ( ) ;
5976 this . #subscriptions. delete ( key ) ;
6077 }
6178 }
6279 }
6380
64- #attachSubscriptionCleanupHandler( win : BrowserWindow ) {
81+ #attachSubscriptionCleanupHandlers( win : BrowserWindow ) {
82+ win . webContents . on ( 'did-start-navigation' , ( { frame } ) => {
83+ debug (
84+ 'Handling webContents `did-start-navigation` event' ,
85+ `webContentsId: ${ win . webContents . id } ` ,
86+ `frameRoutingId: ${ frame . routingId } `
87+ ) ;
88+ this . #cleanUpSubscriptions( {
89+ webContentsId : win . webContents . id ,
90+ frameRoutingId : frame . routingId ,
91+ } ) ;
92+ } ) ;
6593 win . webContents . on ( 'destroyed' , ( ) => {
94+ debug ( 'Handling webContents `destroyed` event' ) ;
6695 this . detachWindow ( win ) ;
6796 } ) ;
6897 }
0 commit comments