From 6bf4183dc39353df2cb163d59a2c249b442435d4 Mon Sep 17 00:00:00 2001 From: Derek Guenther Date: Tue, 28 May 2024 17:07:49 -0400 Subject: [PATCH] Fix crash when calling .destroy() on a BrowserWindow --- .changeset/giant-pandas-approve.md | 5 +++++ .../electron-trpc/src/main/createIPCHandler.ts | 15 ++++++++++----- 2 files changed, 15 insertions(+), 5 deletions(-) create mode 100644 .changeset/giant-pandas-approve.md diff --git a/.changeset/giant-pandas-approve.md b/.changeset/giant-pandas-approve.md new file mode 100644 index 00000000..02bbce14 --- /dev/null +++ b/.changeset/giant-pandas-approve.md @@ -0,0 +1,5 @@ +--- +'electron-trpc': patch +--- + +Fix a crash when calling `.destroy()` on a BrowserWindow. diff --git a/packages/electron-trpc/src/main/createIPCHandler.ts b/packages/electron-trpc/src/main/createIPCHandler.ts index ea4c56a0..dc3cd1e5 100644 --- a/packages/electron-trpc/src/main/createIPCHandler.ts +++ b/packages/electron-trpc/src/main/createIPCHandler.ts @@ -55,11 +55,15 @@ class IPCHandler { this.#attachSubscriptionCleanupHandlers(win); } - detachWindow(win: BrowserWindow) { + detachWindow(win: BrowserWindow, webContentsId?: number) { debug('Detaching window', win.id); + if (win.isDestroyed() && webContentsId === undefined) { + throw new Error('webContentsId is required when calling detachWindow on a destroyed window'); + } + this.#windows = this.#windows.filter((w) => w !== win); - this.#cleanUpSubscriptions({ webContentsId: win.webContents.id }); + this.#cleanUpSubscriptions({ webContentsId: webContentsId ?? win.webContents.id }); } #cleanUpSubscriptions({ @@ -79,23 +83,24 @@ class IPCHandler { } #attachSubscriptionCleanupHandlers(win: BrowserWindow) { + const webContentsId = win.webContents.id; win.webContents.on('did-start-navigation', ({ isSameDocument, frame }) => { // Check if it's a hard navigation if (!isSameDocument) { debug( 'Handling hard navigation event', - `webContentsId: ${win.webContents.id}`, + `webContentsId: ${webContentsId}`, `frameRoutingId: ${frame.routingId}` ); this.#cleanUpSubscriptions({ - webContentsId: win.webContents.id, + webContentsId: webContentsId, frameRoutingId: frame.routingId, }); } }); win.webContents.on('destroyed', () => { debug('Handling webContents `destroyed` event'); - this.detachWindow(win); + this.detachWindow(win, webContentsId); }); } }