Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

feat(electron): add timeout option to electronApp.close() for force-kill escalation (#40613)

Copilot5263a4864b99
diff --git a/docs/src/electron-api/class-electronapplication.md b/docs/src/electron-api/class-electronapplication.md
index 3006801d26..725eef0da6 100644
--- a/docs/src/electron-api/class-electronapplication.md
+++ b/docs/src/electron-api/class-electronapplication.md
@@ -85,6 +85,16 @@ Page to retrieve the window for.
Closes Electron application.
+### option: ElectronApplication.close.timeout
+* since: v1.60
+- `timeout` <[float]>
+
+Maximum time in milliseconds to wait for the Electron application to gracefully close before forcefully terminating it.
+By default, [`method: ElectronApplication.close`] waits indefinitely for the application to exit, which can hang if the
+app has `before-quit` handlers that prevent shutdown, leaky IPC handlers, or child processes that keep it alive. When
+specified, the underlying process is force-killed (SIGKILL on POSIX, `taskkill /T /F` on Windows) if it does not exit
+within the given timeout.
+
## method: ElectronApplication.context
* since: v1.9
- returns: <[BrowserContext]>
diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.ts
index 604fea6d4f..441d3f0fbd 100644
--- a/packages/playwright-client/types/types.d.ts
+++ b/packages/playwright-client/types/types.d.ts
@@ -17043,8 +17043,19 @@ export interface ElectronApplication {
/**
* Closes Electron application.
+ * @param options
*/
- close(): Promise<void>;
+ close(options?: {
+ /**
+ * Maximum time in milliseconds to wait for the Electron application to gracefully close before forcefully terminating
+ * it. By default,
+ * [electronApplication.close([options])](https://playwright.dev/docs/api/class-electronapplication#electron-application-close)
+ * waits indefinitely for the application to exit, which can hang if the app has `before-quit` handlers that prevent
+ * shutdown, leaky IPC handlers, or child processes that keep it alive. When specified, the underlying process is
+ * force-killed (SIGKILL on POSIX, `taskkill /T /F` on Windows) if it does not exit within the given timeout.
+ */
+ timeout?: number;
+ }): Promise<void>;
/**
* This method returns browser context that can be used for setting up context-wide routing, etc.
diff --git a/packages/playwright-core/src/electron/electron.ts b/packages/playwright-core/src/electron/electron.ts
index cc493b7ed1..4a5d5a4785 100644
--- a/packages/playwright-core/src/electron/electron.ts
+++ b/packages/playwright-core/src/electron/electron.ts
@@ -180,7 +180,7 @@ export class Electron implements api.Electron {
const chromeMatch = await Promise.race([chromeMatchPromise, waitForXserverError]);
const browser = await chromium.connectOverCDP(chromeMatch[1], { timeout: progress.timeUntilDeadline(), isLocal: true });
- app = new ElectronApplication(worker, browser, launchedProcess);
+ app = new ElectronApplication(worker, browser, launchedProcess, kill);
await progress.race(app._initialize());
return app;
} catch (error) {
@@ -194,12 +194,13 @@ export class ElectronApplication extends EventEmitter implements api.ElectronApp
private _worker: Worker;
private _browser: Browser;
private _process: childProcess.ChildProcess;
+ private _kill: () => Promise<void>;
private _context: BrowserContext;
private _windows = new Map<Page, JSHandle<BrowserWindow> | undefined>();
private _appHandlePromise = new ManualPromise<JSHandle<ElectronAppType>>();
private _closedPromise: Promise<void> | undefined;
- constructor(worker: Worker, browser: Browser, process: childProcess.ChildProcess) {
+ constructor(worker: Worker, browser: Browser, process: childProcess.ChildProcess, kill: () => Promise<void>) {
super();
this._worker = worker;
@@ -214,6 +215,7 @@ export class ElectronApplication extends EventEmitter implements api.ElectronApp
this._context.close = () => this.close();
this._process = process;
+ this._kill = kill;
}
_onClose() {
@@ -249,7 +251,7 @@ export class ElectronApplication extends EventEmitter implements api.ElectronApp
await this.close();
}
- async close() {
+ async close(options: { timeout?: number } = {}) {
if (!this._closedPromise) {
this._closedPromise = new Promise<void>(f => this.once(Events.ElectronApplication.Close, f));
await this._browser.close();
@@ -257,6 +259,17 @@ export class ElectronApplication extends EventEmitter implements api.ElectronApp
await appHandle.evaluate(({ app }) => app.quit()).catch(() => {});
await this._worker._disconnect();
}
+ if (options.timeout) {
+ let timer: NodeJS.Timeout | undefined;
+ const timedOut = new Promise<boolean>(resolve => {
+ timer = setTimeout(() => resolve(true), options.timeout);
+ });
+ const exited = this._closedPromise.then(() => false);
+ const didTimeout = await Promise.race([exited, timedOut]);
+ clearTimeout(timer);
+ if (didTimeout)
+ await this._kill();
+ }
await this._closedPromise;
}
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index 604fea6d4f..441d3f0fbd 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -17043,8 +17043,19 @@ export interface ElectronApplication {
/**
* Closes Electron application.
+ * @param options
*/
- close(): Promise<void>;
+ close(options?: {
+ /**
+ * Maximum time in milliseconds to wait for the Electron application to gracefully close before forcefully terminating
+ * it. By default,
+ * [electronApplication.close([options])](https://playwright.dev/docs/api/class-electronapplication#electron-application-close)
+ * waits indefinitely for the application to exit, which can hang if the app has `before-quit` handlers that prevent
+ * shutdown, leaky IPC handlers, or child processes that keep it alive. When specified, the underlying process is
+ * force-killed (SIGKILL on POSIX, `taskkill /T /F` on Windows) if it does not exit within the given timeout.
+ */
+ timeout?: number;
+ }): Promise<void>;
/**
* This method returns browser context that can be used for setting up context-wide routing, etc.
diff --git a/tests/electron/electron-app-hang-on-close.js b/tests/electron/electron-app-hang-on-close.js
new file mode 100644
index 0000000000..d469a914f2
--- /dev/null
+++ b/tests/electron/electron-app-hang-on-close.js
@@ -0,0 +1,14 @@
+const assert = require('node:assert/strict');
+const { app } = require('electron');
+
+assert(process.env.PWTEST_ELECTRON_USER_DATA_DIR, 'PWTEST_ELECTRON_USER_DATA_DIR env var is not set');
+app.setPath('appData', process.env.PWTEST_ELECTRON_USER_DATA_DIR);
+
+app.on('window-all-closed', e => e.preventDefault());
+
+// Prevent the app from quitting gracefully to simulate a hung Electron app
+// that requires force-kill escalation.
+app.on('before-quit', e => e.preventDefault());
+
+// Keep the event loop busy so the process never exits on its own.
+setInterval(() => {}, 1000);
diff --git a/tests/electron/electron-app.spec.ts b/tests/electron/electron-app.spec.ts
index 77dc7e0b9a..41fd99a3df 100644
--- a/tests/electron/electron-app.spec.ts
+++ b/tests/electron/electron-app.spec.ts
@@ -69,6 +69,32 @@ test('should fire close event when the app quits itself', async ({ launchElectro
expect([...events].sort()).toEqual(['application(close)', 'context(close)', 'process(exit)']);
});
+test('should force-kill the app when close timeout fires', async ({ launchElectronApp }) => {
+ const electronApp = await launchElectronApp('electron-app-hang-on-close.js');
+ const events = [];
+ electronApp.on('close', () => events.push('application(close)'));
+ electronApp.process().on('exit', () => events.push('process(exit)'));
+ const start = Date.now();
+ await electronApp.close({ timeout: 1000 });
+ const elapsed = Date.now() - start;
+ // Should not wait much longer than the timeout itself.
+ expect(elapsed).toBeLessThan(10000);
+ expect([...events].sort()).toEqual(['application(close)', 'process(exit)']);
+ // A second call should be a noop and not throw.
+ await electronApp.close({ timeout: 1000 });
+});
+
+test('should not force-kill the app when close completes within timeout', async ({ launchElectronApp }) => {
+ const electronApp = await launchElectronApp('electron-app.js');
+ const events = [];
+ electronApp.on('close', () => events.push('application(close)'));
+ electronApp.process().on('exit', code => events.push(`process(exit:${code})`));
+ await electronApp.close({ timeout: 30000 });
+ expect(events).toContain('application(close)');
+ // Exit code 0 indicates a graceful shutdown (force-kill would yield null).
+ expect(events).toContain('process(exit:0)');
+});
+
test('should fire console events', async ({ launchElectronApp }) => {
const electronApp = await launchElectronApp('electron-app.js');
const messages = [];