Browse Source

fix: getting focused window with destroyed webContents (#33540)

* fix: getting focused window with destroyed webContents

* fix: add extra safeguards

Co-authored-by: Shelley Vohr <[email protected]>
trop[bot] 3 years ago
parent
commit
a6c71cc914
2 changed files with 23 additions and 1 deletions
  1. 4 1
      lib/browser/api/browser-window.ts
  2. 19 0
      spec-main/api-browser-window-spec.ts

+ 4 - 1
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;
 };

+ 19 - 0
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 });