🐛 fix: handle will-prevent-unload event to allow app quit (#11406)

fix: handle will-prevent-unload event to allow app quit
This commit is contained in:
Arvin Xu
2026-01-11 16:18:56 +08:00
committed by GitHub
parent 6d1037a424
commit cbeb01399f
2 changed files with 46 additions and 0 deletions

View File

@@ -184,6 +184,20 @@ export default class Browser {
this.setupReadyToShowListener(browserWindow);
this.setupCloseListener(browserWindow);
this.setupFocusListener(browserWindow);
this.setupWillPreventUnloadListener(browserWindow);
}
private setupWillPreventUnloadListener(browserWindow: BrowserWindow): void {
logger.debug(`[${this.identifier}] Setting up 'will-prevent-unload' event listener.`);
browserWindow.webContents.on('will-prevent-unload', (event) => {
logger.debug(
`[${this.identifier}] 'will-prevent-unload' fired. isQuiting: ${this.app.isQuiting}`,
);
if (this.app.isQuiting) {
logger.info(`[${this.identifier}] App is quitting, ignoring beforeunload cancellation.`);
event.preventDefault();
}
});
}
private setupReadyToShowListener(browserWindow: BrowserWindow): void {

View File

@@ -40,6 +40,7 @@ const { mockBrowserWindow, mockNativeTheme, mockIpcMain, mockScreen, MockBrowser
onHeadersReceived: vi.fn(),
},
},
on: vi.fn(),
},
};
@@ -646,4 +647,35 @@ describe('Browser', () => {
expect(mockBrowserWindow.setBackgroundColor).not.toHaveBeenCalled();
});
});
describe('will-prevent-unload event handling', () => {
let willPreventUnloadHandler: (e: any) => void;
beforeEach(() => {
// Get the will-prevent-unload handler registered during initialization
willPreventUnloadHandler = mockBrowserWindow.webContents.on.mock.calls.find(
(call) => call[0] === 'will-prevent-unload',
)?.[1];
});
it('should call preventDefault when app is quitting', () => {
(mockApp as any).isQuiting = true;
const mockEvent = { preventDefault: vi.fn() };
expect(willPreventUnloadHandler).toBeDefined();
willPreventUnloadHandler(mockEvent);
expect(mockEvent.preventDefault).toHaveBeenCalled();
});
it('should not call preventDefault when app is not quitting', () => {
(mockApp as any).isQuiting = false;
const mockEvent = { preventDefault: vi.fn() };
expect(willPreventUnloadHandler).toBeDefined();
willPreventUnloadHandler(mockEvent);
expect(mockEvent.preventDefault).not.toHaveBeenCalled();
});
});
});