Skip to content

Pages & JavaScript

A Pam\Browser\Page is one browser tab with its own CDP session. You create pages from a launched Browser, then navigate them, run JavaScript in them, and read the results back as plain PHP values.

use Pam\Browser\Browser;
$browser = Browser::launch();
$page = $browser->newPage('https://example.com');
$heading = $page->evaluate('document.querySelector("h1").textContent');

newPage() creates a target, attaches to it, enables the Page and Runtime domains, and, when you pass a URL, navigates and waits for the load event:

$blank = $browser->newPage(); // about:blank
$page = $browser->newPage('https://example.com', 20.0); // wait up to 20 s

Each page exposes its CDP identifiers as read-only properties:

$page->targetId; // the CDP target id
$page->sessionId; // the flattened CDP session id

If you only need a target without attaching to it, createTarget() returns its id:

$targetId = $browser->createTarget('https://example.com');

navigate() loads a URL and blocks until the page fires its load event:

$page->navigate('https://example.com/pricing');
$page->navigate('https://example.com/slow', timeoutSeconds: 60.0);

If Chrome reports a navigation error (for example a DNS failure), navigate() throws Pam\Browser\Exception\ProtocolException with Chrome’s error text, such as Page navigation failed: net::ERR_NAME_NOT_RESOLVED. A timeout also throws ProtocolException.

data: URLs work too, which is handy for tests and for rendering HTML you generated:

$page->navigate('data:text/html,<h1>Invoice 42</h1>');

evaluate() runs an expression in the page and returns its value, converted to PHP:

$page->evaluate('document.title'); // string
$page->evaluate('document.querySelectorAll("a").length'); // int
$page->evaluate('({ width: innerWidth, height: innerHeight })'); // array
$page->evaluate('undefined'); // null

Promises are awaited by default, so asynchronous code returns its resolved value:

$status = $page->evaluate('fetch("/api/health").then(r => r.status)');

Pass awaitPromise: false to get the value immediately without awaiting it.

The value is returned by value, so it must be JSON-serializable. DOM nodes and functions come back as empty arrays or null; extract the fields you need in JavaScript instead.

When the script throws, evaluate() throws a ProtocolException that contains the JavaScript error:

use Pam\Browser\Exception\ProtocolException;
try {
$page->evaluate('missingFunction()');
} catch (ProtocolException $exception) {
echo $exception->getMessage();
// JavaScript evaluation failed: ReferenceError: missingFunction is not defined ...
}

Many pages keep rendering after the load event. waitForFunction() polls an expression until it returns something other than false or null, and returns that value:

$count = $page->waitForFunction(
'document.querySelectorAll(".result").length || null',
timeoutSeconds: 10.0,
pollIntervalSeconds: 0.1,
);

Polling uses Pam\Async\delay() when it is available, so other fibers keep running while you wait. On timeout it throws ProtocolException with Timed out waiting for a JavaScript condition.

addScriptOnNewDocument() registers a script that runs before any page script on every subsequent navigation, and returns its CDP identifier:

$page->addScriptOnNewDocument('window.__acme = { startedAt: Date.now() };');
$page->navigate('https://example.com');
$page->evaluate('typeof window.__acme'); // "object"

captureScreenshot() returns the visible viewport as PNG bytes:

file_put_contents(__DIR__.'/example.png', $page->captureScreenshot());

The bytes are validated as a PNG before they are returned. Combine it with the --window-size launch argument to control the size.

$page->setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AcmeBot/1.0');
$page->setBypassCsp(true); // let injected scripts run on pages with a strict Content-Security-Policy

Both apply to the page they are called on.

PAM Browser uses the CDP Fetch domain for three focused features.

Launch Chrome with --proxy-server, then give the page the proxy credentials. They are answered automatically whenever the proxy asks:

$browser = Browser::launch(new LaunchOptions(arguments: [
'--proxy-server=http://proxy.example.com:3128',
]));
$page = $browser->newPage();
$page->authenticate('alice', getenv('PROXY_PASSWORD'));
$page->navigate('https://example.com');

serveDocument() answers the top-level document request for one exact URL with HTML you provide. Other requests (scripts, images, API calls) still go to the network:

$page->serveDocument('https://example.com/preview', '<h1>Draft preview</h1>');
$page->navigate('https://example.com/preview');

This is useful for loading a cached copy of a page while keeping its real origin, so relative URLs and cookies still behave.

captureDocument() calls your callback with the body of every response whose URL matches exactly:

$page->captureDocument('https://example.com/', function (string $html): void {
file_put_contents(__DIR__.'/example.html', $html);
});
$page->navigate('https://example.com/');

The callback runs while PAM Browser processes CDP events, for example during navigate(), evaluate(), or pump().