From a6c71cc9140617089eee012cd4021b6c49ce0d3f Mon Sep 17 00:00:00 2001 From: "trop[bot]" <37223003+trop[bot]@users.noreply.github.com> Date: Tue, 19 Apr 2022 09:20:04 +0900 Subject: [PATCH] fix: getting focused window with destroyed webContents (#33540) * fix: getting focused window with destroyed webContents * fix: add extra safeguards Co-authored-by: Shelley Vohr --- 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 62630bfffb2f5..d20ea0bda5571 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 1a02fd7ca4bdc..7bc5ba5f6c90c 100644 --- a/spec-main/api-browser-window-spec.ts +++ b/spec-main/api-browser-window-spec.ts @@ -3717,6 +3717,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 });