Skip to content

Commit

Permalink
Fix crash when calling .destroy() on a BrowserWindow
Browse files Browse the repository at this point in the history
  • Loading branch information
dguenther authored and jsonnull committed Dec 7, 2024
1 parent bf2c1a4 commit 6bf4183
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/giant-pandas-approve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'electron-trpc': patch
---

Fix a crash when calling `.destroy()` on a BrowserWindow.
15 changes: 10 additions & 5 deletions packages/electron-trpc/src/main/createIPCHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,15 @@ class IPCHandler<TRouter extends AnyRouter> {
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({
Expand All @@ -79,23 +83,24 @@ class IPCHandler<TRouter extends AnyRouter> {
}

#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);
});
}
}
Expand Down

0 comments on commit 6bf4183

Please sign in to comment.