From d1ea62c3e835abc20e30e64d76823edfa5cbe75c Mon Sep 17 00:00:00 2001 From: Shelley Vohr Date: Tue, 29 Mar 2022 18:22:58 +0200 Subject: [PATCH] fix: getting focused window with destroyed webContents (#33404) * fix: getting focused window with destroyed webContents * fix: add extra safeguards --- lib/browser/api/browser-window.ts | 5 ++++- spec-main/api-browser-window-spec.ts | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/browser/api/browser-window.ts b/lib/browser/api/browser-window.ts index 62630bfffb2f..d20ea0bda557 100644 --- a/lib/browser/api/browser-window.ts +++ b/lib/browser/api/browser-window.ts @@ -72,7 +72,10 @@ BrowserWindow.getAllWindows = () => { BrowserWindow.getFocusedWindow = () => { for (const window of BrowserWindow.getAllWindows()) { - if (window.isFocused() || window.isDevToolsFocused()) return window; + const hasWC = window.webContents && !window.webContents.isDestroyed(); + if (!window.isDestroyed() && hasWC) { + if (window.isFocused() || window.isDevToolsFocused()) return window; + } } return null; }; diff --git a/spec-main/api-browser-window-spec.ts b/spec-main/api-browser-window-spec.ts index d4d4a70799a1..19c08c070081 100644 --- a/spec-main/api-browser-window-spec.ts +++ b/spec-main/api-browser-window-spec.ts @@ -3725,6 +3725,25 @@ describe('BrowserWindow module', () => { expect(w.getChildWindows().length).to.equal(0); }); + it('closes a grandchild window when a middle child window is destroyed', (done) => { + const w = new BrowserWindow(); + + w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); + w.webContents.executeJavaScript('window.open("")'); + + w.webContents.on('did-create-window', async (window) => { + const childWindow = new BrowserWindow({ parent: window }); + + await delay(); + window.close(); + + childWindow.on('closed', () => { + expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); + done(); + }); + }); + }); + it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w });