Skip to content

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

fix(route): don't get stalled by "runBeforeUnload" (#38748)

Simon Knott03a996fc4151
diff --git a/packages/playwright-core/src/client/page.ts b/packages/playwright-core/src/client/page.ts
index ad4cf80011..61cc51380e 100644
--- a/packages/playwright-core/src/client/page.ts
+++ b/packages/playwright-core/src/client/page.ts
@@ -631,7 +631,8 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Page
async close(options: { runBeforeUnload?: boolean, reason?: string } = {}) {
this._closeReason = options.reason;
- this._closeWasCalled = true;
+ if (!options.runBeforeUnload)
+ this._closeWasCalled = true;
try {
if (this._ownedContext)
await this._ownedContext.close();
diff --git a/tests/page/page-route.spec.ts b/tests/page/page-route.spec.ts
index b601fc95fd..d0f2418e94 100644
--- a/tests/page/page-route.spec.ts
+++ b/tests/page/page-route.spec.ts
@@ -1069,3 +1069,25 @@ it('should be able to intercept every navigation to a page controlled by service
await page.goto(URL);
expect(interceptions).toBe(2);
});
+
+it('does not get stalled by beforeUnload', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/38731' } }, async ({ page, server }) => {
+ await page.goto(server.HELLO_WORLD);
+
+ await page.evaluate(() => {
+ window.addEventListener('beforeunload', event => {
+ event.preventDefault();
+ });
+ });
+ page.on('dialog', dialog => dialog.dismiss());
+
+ // We have to interact with a page so that 'beforeunload' handlers
+ // fire.
+ await page.click('body');
+
+ await page.route('**/api', route => route.fulfill({ status: 200, body: 'ok' }));
+ await page.evaluate(async () => fetch(new URL('/api', window.location.href)));
+
+ await page.close({ runBeforeUnload: true });
+
+ await page.evaluate(async () => fetch(new URL('/api', window.location.href)));
+});