Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions bin/lib/handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -343,9 +343,7 @@ class ContextHandler extends BaseHandler {

for (const [pageId, mappedContextId] of this.pageContexts.entries()) {
if (mappedContextId === contextId) {
this.pageContexts.delete(pageId);
this.pages.delete(pageId);
RouteUtils.forgetRoutes(this.routes, this.routeHandlers, pageId);
this.cleanupPageResources(this.pages.get(pageId), pageId);
}
}

Expand Down Expand Up @@ -794,6 +792,8 @@ class PageHandler extends BaseHandler {
const popupPageId = result.result.popupPageId;
const popup = result.result.popup;

if (popup?.isClosed()) throw new Error('Popup closed before callback completed.');

if (popup && !this.pages.has(popupPageId)) {
// Re-register the popup page in the main pages Map
this.pages.set(popupPageId, popup);
Expand Down
3 changes: 3 additions & 0 deletions bin/lib/popup-coordinator.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ class PopupCoordinator {
logger.error('Popup is null or undefined', { requestId, ownerId });
return { popupPageId: null };
}

if (popup.isClosed()) throw new Error('Popup closed before callback completed.');

const popupPageId = generateId('page');

// Register popup and context mapping
Expand Down
154 changes: 94 additions & 60 deletions bin/playwright-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ class PlaywrightServer extends BaseHandler {
this.pages = new Map();
this.pageContexts = new Map();
this.responses = new Map();
this.responseIds = new WeakMap();
this.responsePages = new Map();
this.routes = new Map();
this.routeHandlers = new Map();
this.dialogs = new Map();
Expand All @@ -40,7 +42,8 @@ class PlaywrightServer extends BaseHandler {
extractRequestData: this.extractRequestData.bind(this), serializeResponse: this.serializeResponse.bind(this),
serializeConsoleMessage: this.serializeConsoleMessage.bind(this),
sendFramedResponse,
setupPageEventListeners: this.setupPageEventListeners.bind(this)
setupPageEventListeners: this.setupPageEventListeners.bind(this),
cleanupPageResources: this.cleanupPageResources.bind(this)
};
this.apiRequestHandler = new APIRequestHandler(deps);
this.contextHandler = new ContextHandler(deps);
Expand Down Expand Up @@ -175,11 +178,11 @@ class PlaywrightServer extends BaseHandler {
setupPageEventListeners(page, pageId) {
['console', 'dialog', 'request', 'response', 'requestfailed', 'download'].forEach(eventName => {
page.on(eventName, ErrorHandler.wrapHandler((eventData) => {
const params = eventName === 'download' ? this.registerDownload(eventData, page) : this.formatEventParams(eventName, eventData);
const params = eventName === 'download' ? this.registerDownload(eventData, page) : this.formatEventParams(eventName, eventData, page);
sendFramedResponse({ objectId: pageId, event: eventName, params });
}));
});
page.once('close', () => RouteUtils.forgetRoutes(this.routes, this.routeHandlers, pageId));
page.once('close', () => this.cleanupPageResources(page, pageId));
}

// Pages opened by the browser itself (window.open(), target="_blank", ...) never go through
Expand All @@ -188,6 +191,8 @@ class PlaywrightServer extends BaseHandler {
registerContextPopups(context, contextId) {
context.on('page', (newPage) => {
setImmediate(() => {
if (newPage.isClosed()) return;

for (const existing of this.pages.values()) {
if (existing === newPage) return;
}
Expand All @@ -196,7 +201,7 @@ class PlaywrightServer extends BaseHandler {
});
});
// A context also closes with its browser, which never goes through closeContext().
context.once('close', () => RouteUtils.forgetRoutes(this.routes, this.routeHandlers, contextId));
context.once('close', () => this.contextHandler.cleanupContextResources(contextId));
}

// One id per download, whether PHP learns about it from the page event or from
Expand All @@ -221,7 +226,7 @@ class PlaywrightServer extends BaseHandler {
return pageId;
}

formatEventParams(eventName, eventData) {
formatEventParams(eventName, eventData, page) {
const formatters = {
console: () => this.serializeConsoleMessage(eventData),
dialog: () => {
Expand All @@ -231,7 +236,7 @@ class PlaywrightServer extends BaseHandler {
},
request: () => ({ request: this.extractRequestData(eventData) }),
requestfailed: () => ({ request: this.extractRequestData(eventData) }),
response: () => ({ response: this.serializeResponse(eventData) })
response: () => ({ response: this.serializeResponse(eventData, page) })
};
return formatters[eventName] ? formatters[eventName]() : {};
}
Expand Down Expand Up @@ -270,10 +275,35 @@ class PlaywrightServer extends BaseHandler {
return { url: req.url(), method: req.method(), headers: req.headers(), postData: postData ?? null, postDataBuffer, resourceType: req.resourceType ? req.resourceType() : 'document', response: existingResponse, isNavigationRequest: req.isNavigationRequest ? req.isNavigationRequest() : false };
}

serializeResponse(response) {
cleanupPageResources(page, pageId) {
const contextId = this.pageContexts.get(pageId);
this.pages.delete(pageId);
this.pageContexts.delete(pageId);
RouteUtils.forgetRoutes(this.routes, this.routeHandlers, pageId);

for (const [responseId, owner] of this.responsePages) {
if (owner !== page) continue;

this.responses.delete(responseId);
this.responsePages.delete(responseId);
}

sendFramedResponse({ objectId: pageId, event: 'close', params: {} });

if (contextId) sendFramedResponse({ objectId: contextId, event: 'pageClosed', params: { pageId } });
}

serializeResponse(response, page = null) {
if (!response) return null;
const responseId = this.generateId('response');
this.responses.set(responseId, response);

let responseId = this.responseIds.get(response);

if (!responseId) {
responseId = this.generateId('response');
this.responseIds.set(response, responseId);
this.responses.set(responseId, response);
this.responsePages.set(responseId, page || response.frame().page());
}
return { responseId, url: response.url(), status: response.status(), statusText: response.statusText(), headers: response.headers() };
}

Expand Down Expand Up @@ -470,62 +500,66 @@ class PlaywrightServer extends BaseHandler {
}
}

const server = new PlaywrightServer();
let inputBuffer = Buffer.alloc(0);

sendFramedResponse({ type: 'ready', message: 'READY' });

process.stdin.on('data', ErrorHandler.wrapHandler(async (chunk) => {
inputBuffer = Buffer.concat([inputBuffer, chunk]);
try {
const decoded = LspFraming.decode(inputBuffer);
inputBuffer = decoded.remainingBuffer;
for (const messageContent of decoded.messages) {
if (!messageContent.trim()) continue;
let command;
const fail = (error) => {
logger.error('SERVER ERROR', { error: error.message, stack: error.stack, command: messageContent });
const errorResponse = { error: error.message, parseError: true };
if (command?.requestId) errorResponse.requestId = command.requestId;
sendFramedResponse(errorResponse);
};
try {
command = JSON.parse(messageContent);
// Not awaited, so a slow command cannot hold back the rest of the chunk.
server.handleCommand(command).then((result) => { if (result) sendFramedResponse(result); }, fail);
} catch (error) {
fail(error);
module.exports = { PlaywrightServer };

if (require.main === module) {
const server = new PlaywrightServer();
let inputBuffer = Buffer.alloc(0);

sendFramedResponse({ type: 'ready', message: 'READY' });

process.stdin.on('data', ErrorHandler.wrapHandler(async (chunk) => {
inputBuffer = Buffer.concat([inputBuffer, chunk]);
try {
const decoded = LspFraming.decode(inputBuffer);
inputBuffer = decoded.remainingBuffer;
for (const messageContent of decoded.messages) {
if (!messageContent.trim()) continue;
let command;
const fail = (error) => {
logger.error('SERVER ERROR', { error: error.message, stack: error.stack, command: messageContent });
const errorResponse = { error: error.message, parseError: true };
if (command?.requestId) errorResponse.requestId = command.requestId;
sendFramedResponse(errorResponse);
};
try {
command = JSON.parse(messageContent);
// Not awaited, so a slow command cannot hold back the rest of the chunk.
server.handleCommand(command).then((result) => { if (result) sendFramedResponse(result); }, fail);
} catch (error) {
fail(error);
}
}
} catch (error) {
logger.error('LSP FRAMING ERROR', { error: error.message, stack: error.stack });
sendFramedResponse({ error: 'LSP framing error: ' + error.message });
}
} catch (error) {
logger.error('LSP FRAMING ERROR', { error: error.message, stack: error.stack });
sendFramedResponse({ error: 'LSP framing error: ' + error.message });
}
}));
}));

// The PHP process owns this server. Once it is gone, nothing will ever arrive on
// stdin again and every browser we hold becomes an orphan reparented to init.
// stdin closing covers the cases no PHP-side shutdown hook can reach: SIGKILL,
// a fatal error, or SIGTERM, none of which run register_shutdown_function.
let shuttingDown = false;

// The PHP process owns this server. Once it is gone, nothing will ever arrive on
// stdin again and every browser we hold becomes an orphan reparented to init.
// stdin closing covers the cases no PHP-side shutdown hook can reach: SIGKILL,
// a fatal error, or SIGTERM, none of which run register_shutdown_function.
let shuttingDown = false;
async function shutdown(reason) {
if (shuttingDown) return;
shuttingDown = true;

async function shutdown(reason) {
if (shuttingDown) return;
shuttingDown = true;
// A browser that refuses to close must not wedge the process: exiting without
// cleanup still lets Chromium notice the broken pipe, hanging here does not.
const watchdog = setTimeout(() => process.exit(1), 5000);
watchdog.unref();

// A browser that refuses to close must not wedge the process: exiting without
// cleanup still lets Chromium notice the broken pipe, hanging here does not.
const watchdog = setTimeout(() => process.exit(1), 5000);
watchdog.unref();
try {
logger.info('Parent gone, shutting down', { reason });
} catch {}

try {
logger.info('Parent gone, shutting down', { reason });
} catch {}
await server.exit();
}

await server.exit();
process.stdin.on('end', () => shutdown('stdin end'));
process.stdin.on('close', () => shutdown('stdin close'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGHUP', () => shutdown('SIGHUP'));
}

process.stdin.on('end', () => shutdown('stdin end'));
process.stdin.on('close', () => shutdown('stdin close'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGHUP', () => shutdown('SIGHUP'));
4 changes: 4 additions & 0 deletions docs/guide/core-concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,7 @@ $signInButton->click();

By understanding and using these four core concepts, you can build powerful, reliable, and maintainable browser
automation scripts and tests.

## Resource lifetimes

Response handles remain available for repeated reads while their page is open and are released when the page, context, or browser closes. Close pages and contexts between jobs in a long-running worker. One indefinitely open page can still retain its response history.
32 changes: 32 additions & 0 deletions tests/Integration/Bridge/LifecycleBridgeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

/*
* This file is part of the community-maintained Playwright PHP project.
* It is not affiliated with or endorsed by Microsoft.
*
* (c) 2025-Present - Playwright PHP - https://github.com/playwright-php
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Playwright\Tests\Integration\Bridge;

use PHPUnit\Framework\Attributes\CoversNothing;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\Process;

#[CoversNothing]
final class LifecycleBridgeTest extends TestCase
{
public function testBridgeBoundariesAndResourceLifetimes(): void
{
$process = new Process(['node', '--test', __DIR__.'/lifecycle.test.cjs']);
$process->setTimeout(30);
$process->run();

$this->assertSame(0, $process->getExitCode(), $process->getOutput().$process->getErrorOutput());
}
}
37 changes: 37 additions & 0 deletions tests/Integration/Bridge/lifecycle.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { EventEmitter } = require('node:events');
const { LspFraming } = require('../../../bin/lib/core');
const { PlaywrightServer } = require('../../../bin/playwright-server');

test('response identifiers are reused and released with their owning page', () => {
const server = new PlaywrightServer();
const page = new EventEmitter();
const response = { url: () => 'https://example.test', status: () => 200, statusText: () => 'OK', headers: () => ({}), frame: () => ({ page: () => page }) };
const id = server.registerPage(page, 'context_1');
const first = server.serializeResponse(response);
assert.equal(server.serializeResponse(response).responseId, first.responseId);
assert.equal(server.responses.size, 1);
const write = process.stdout.write;
let output = '';
process.stdout.write = (data, callback) => { output += data; callback?.(); return true; };
try { page.emit('close'); } finally { process.stdout.write = write; }
assert.equal(server.responses.size, 0);
assert.equal(server.responsePages.size, 0);
assert.equal(server.pages.has(id), false);
assert.equal(server.pageContexts.has(id), false);
const events = LspFraming.decode(Buffer.from(output));
assert.deepEqual(events.messages.map(message => JSON.parse(message).event), ['close', 'pageClosed']);
});

for (const mode of ['page', 'context']) {
test(`${mode} popup coordination does not register an already closed popup`, async () => {
const { PopupCoordinator } = require('../../../bin/lib/popup-coordinator');
const pages = new Map();
const pageContexts = new Map([['owner', 'context']]);
const phases = PopupCoordinator.createPopupPhases(mode, { pages, pageContexts, generateId: () => 'popup' });
await assert.rejects(phases[1].handler({ popupPromise: Promise.resolve({ isClosed: () => true }), requestId: 'wait', pageId: 'owner', contextId: 'context' }), /Popup closed/);
assert.equal(pages.size, 0);
assert.equal(pageContexts.size, 1);
});
}
20 changes: 20 additions & 0 deletions tests/Integration/Popup/PopupFailureTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,26 @@ public static function popupOwners(): iterable
yield 'context' => [true];
}

#[DataProvider('popupOwners')]
public function testPopupClosedDuringTheActionIsNotRegisteredAgain(bool $useContext): void
{
$owner = $useContext ? $this->context : $this->page;

try {
$owner->waitForPopup(function (): void {
$this->page->evaluate('() => { const popup = window.open("about:blank"); setTimeout(() => popup.close(), 0); }');
usleep(50000);
$this->page->title();
}, ['timeout' => 1000]);
$this->fail('A popup that closed during the action must not be registered again.');
} catch (PlaywrightException $exception) {
$this->assertStringContainsString('Popup closed', $exception->getMessage());
}

$this->page->title();
$this->assertCount(1, $this->context->pages());
}

#[DataProvider('popupOwners')]
public function testClosingTheOwnerPreservesTheFailure(bool $useContext): void
{
Expand Down
Loading