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
12 changes: 4 additions & 8 deletions bin/lib/handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -520,14 +520,10 @@ class PageHandler extends BaseHandler {

async waitForFunction(page, command) {
try {
let func;
try {
func = eval(`(${command.pageFunction})`);
} catch (e) {
func = command.pageFunction;
}

await page.waitForFunction(func, command.arg, command.options);
await page.waitForFunction(({ expression, arg }) => {
const value = eval(`(${expression})`);
return typeof value === 'function' ? value(arg) : value;
}, { expression: command.pageFunction, arg: command.arg }, command.options);
} catch (error) {
logger.error('PAGE WAITFORFUNCTION ERROR', { message: error.message });
throw error;
Expand Down
108 changes: 56 additions & 52 deletions bin/playwright-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ class PlaywrightServer extends BaseHandler {
if (command?.options?.env?.PWDEBUG) process.env.PWDEBUG = String(command.options.env.PWDEBUG);
if (command.browser === 'chromium' || !command.browser) {
options.args = [
'--no-sandbox', '--disable-dev-shm-usage', '--disable-web-security',
'--disable-dev-shm-usage',
'--disable-background-timer-throttling', '--disable-backgrounding-occluded-windows', '--disable-renderer-backgrounding',
'--disable-field-trial-config', '--disable-ipc-flooding-protection', '--disable-popup-blocking', ...(options.args || [])
];
Expand Down Expand Up @@ -470,62 +470,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.

## Browser execution

Chromium launches keep the browser's normal same-origin checks. Tests that deliberately need different behavior can supply their own Chromium arguments through `args`.
32 changes: 32 additions & 0 deletions tests/Integration/Bridge/BrowserBridgeTest.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 BrowserBridgeTest extends TestCase
{
public function testBridgeBoundariesAndResourceLifetimes(): void
{
$process = new Process(['node', '--test', __DIR__.'/browser.test.cjs']);
$process->setTimeout(30);
$process->run();

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

test('Chromium arguments keep origin checks and caller sandbox choices', () => {
const server = new PlaywrightServer();
const options = server.buildLaunchOptions({ browser: 'chromium', options: { chromiumSandbox: true } });
assert.equal(options.args.includes('--disable-web-security'), false);
assert.equal(options.args.includes('--no-sandbox'), false);
assert.equal(options.chromiumSandbox, true);
assert.equal(server.buildLaunchOptions({ options: { args: ['--disable-web-security'] } }).args.includes('--disable-web-security'), true);
});

test('browser predicates stay in their browser realm and keep arguments', async () => {
delete globalThis.hostPredicateMarker;
const page = {
waitForFunction: async (callback, payload, options) => {
assert.deepEqual(options, { polling: 20, timeout: 1000 });
const result = vm.runInNewContext(`(${callback.toString()})(payload)`, { payload, document: { title: 'Ready' } });
assert.equal(result, true);
},
};
const handler = new PageHandler();
await handler.waitForFunction(page, {
pageFunction: '(globalThis.hostPredicateMarker = true, arg => document.title === arg)',
arg: 'Ready', options: { polling: 20, timeout: 1000 },
});
assert.equal(globalThis.hostPredicateMarker, undefined);
});
73 changes: 73 additions & 0 deletions tests/Integration/Browser/BrowserBoundaryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?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\Browser;

use PHPUnit\Framework\Attributes\CoversNothing;
use PHPUnit\Framework\TestCase;
use Playwright\Exception\TimeoutException;
use Playwright\Network\RouteInterface;
use Playwright\Testing\PlaywrightTestCaseTrait;

#[CoversNothing]
final class BrowserBoundaryTest extends TestCase
{
use PlaywrightTestCaseTrait;

protected function setUp(): void
{
$this->setUpPlaywright();
$this->page->route('https://private.example/**', static function (RouteInterface $route): void {
$route->fulfill(['contentType' => 'text/html', 'headers' => ['access-control-allow-origin' => 'https://private.example'], 'body' => '<p>private-content</p><input id="password">']);
});
}

protected function tearDown(): void
{
$this->tearDownPlaywright();
}

public function testDefaultLaunchKeepsCrossOriginReadsBlocked(): void
{
$result = $this->page->evaluate('async () => { try { return await (await fetch("https://private.example/data")).text(); } catch { return "blocked"; } }');
$this->assertSame('blocked', $result);
$this->page->goto('https://private.example/data');
$this->assertSame('private-content', $this->page->locator('p')->textContent());
}

public function testWaitPredicatesKeepExpressionsFunctionsAndArguments(): void
{
$this->page->setContent('<title>loading</title><script>setTimeout(() => document.title = "ready", 100)</script>');
$this->page->waitForFunction('(expected) => document.title === expected', 'ready', ['timeout' => 1000, 'polling' => 20]);
$this->page->waitForFunction('document.title === "ready"', null, ['timeout' => 1000]);
$this->page->waitForFunction('return document.title === arg;', 'ready', ['timeout' => 1000]);
$this->assertSame('ready', $this->page->title());
}

public function testWaitPredicatesWorkWithRestrictiveContentSecurityPolicy(): void
{
$this->page->route('https://private.example/csp', static function (RouteInterface $route): void {
$route->fulfill(['contentType' => 'text/html', 'headers' => ['content-security-policy' => "default-src 'none'; script-src 'none'"], 'body' => '<title>ready</title>']);
});
$this->page->goto('https://private.example/csp');
$this->page->waitForFunction('() => document.title === "ready"', null, ['timeout' => 1000]);
$this->assertSame('ready', $this->page->title());
}

public function testFalseFunctionPredicatesStillTimeOut(): void
{
$this->expectException(TimeoutException::class);
$this->page->waitForFunction('() => false', null, ['timeout' => 50]);
}
}
Loading