JavaScript Pages
Most “JavaScript sites” do not need a browser. Server-rendered frameworks such as Next.js, Nuxt and Remix ship the page’s data inside the HTML so the client can hydrate it, and single-page apps load their content from JSON APIs that you can call directly. Both are faster and lighter to read than a rendered page.
PAM Crawl climbs a ladder and stops at the first rung that gets the content:
- Hydration data, no JavaScript.
$page->embeddedreads the state the server already shipped. - The JSON APIs behind the page.
$page->api()finds and verifies the endpoints the app calls. - Render only when needed.
->render()uses plain HTTP first and renders only pages that need it. - Render everything.
->browser()renders every page in a browser, like Crawl4AI.
Rungs 1 and 2 are part of the core package. Rungs 3 and 4 need the optional
pushinbr/pam-crawl-browser plugin.
Detecting app shells
Section titled “Detecting app shells”A client-rendered app often serves an almost empty HTML “shell” that JavaScript fills in later.
$page->isShell tells you when plain HTTP got such a shell, and $page->blocked tells you when a
bot wall (a challenge page) answered instead of the site:
$page = Crawl::url('https://app.example.com/products/42')->get();
if ($page->isShell) { // little HTML content: look at $page->embedded, $page->api(), or render it}Hydration data
Section titled “Hydration data”$page->embedded is an array of the data JavaScript apps embed in their HTML, decoded without
running any code. It covers Next.js (__NEXT_DATA__ under the next key, and App Router flight
data under nextFlight), Nuxt 2 and 3 (nuxt), Remix, Gatsby, Apollo and Redux state globals, and
any <script type="application/json"> element (under its id).
use Pam\Crawl\Crawl;
$html = <<<'HTML'<html><body><div id="__next"></div><script id="__NEXT_DATA__" type="application/json"> {"props":{"pageProps":{"product":{"name":"Trail Shoe","price":89.9,"stock":12}}}}</script></body></html>HTML;
$page = Crawl::html($html, 'https://shop.example.com/p/trail-shoe')->get();
var_dump($page->isShell); // trueecho $page->embedded['next']['props']['pageProps']['product']['name']; // Trail ShoeMapping hydration data to objects
Section titled “Mapping hydration data to objects”The #[Embedded] attribute reads a dot path from the same data. * matches any key and a leading
.. searches at any depth, which keeps your DTO working when the app reshuffles its state:
use Pam\Crawl\Extract\Embedded;
final readonly class Product{ public function __construct( #[Embedded('..product.name')] public string $name, #[Embedded('..product.price')] public float $price, #[Embedded('next.props.pageProps.product.stock')] public int $stock, ) {}}
$product = $page->extract(Product::class); // Trail Shoe, 89.9, 12See Extraction for every attribute.
Discovering JSON APIs
Section titled “Discovering JSON APIs”$page->api() finds the JSON endpoints behind a page without running JavaScript: Next.js
/_next/data routes, Nuxt _payload.json, Gatsby page-data, the WordPress REST API, Shopify
.json endpoints, and endpoints mined from the page’s JavaScript bundles. Candidates are verified
with GET requests and verified endpoints come first, with their decoded data:
use Pam\Crawl\Crawl;
$page = Crawl::url('https://wordpress.org/news/')->get();
foreach ($page->api() as $endpoint) { printf( "%s %s %d %s\n", $endpoint->verified ? 'verified ' : 'candidate', $endpoint->source, $endpoint->status, $endpoint->url, ); // $endpoint->data holds the decoded JSON of verified endpoints}Pass verify: false to list candidates without requesting them.
Sessions, cookies and forms
Section titled “Sessions, cookies and forms”Many pages need state rather than JavaScript. The core crawler handles the common cases over plain HTTP:
use Pam\Crawl\Crawl;
$jar = __DIR__.'/storage/crawl.cookies';
// Log in once: cookies set by the response are stored in the jar file.Crawl::url('https://app.example.com/login') ->session($jar) ->get();
// Later crawls, even in another process, send the same cookies.$page = Crawl::url('https://app.example.com/account')->session($jar)->get();| Method | Description |
|---|---|
session(?string $cookieJarFile = null) |
Share cookies across all requests of a crawl, and across runs when a file is given. |
cookies(array $cookies) |
Send fixed cookies with every request. |
headers(array $headers) / header(string $name, string $value) |
Send extra headers, such as an Authorization token. |
post(string $body, string $contentType = 'application/x-www-form-urlencoded') |
Send a POST request instead of a GET. |
Only crawl authenticated areas you are allowed to access; see Responsible Use.
Rendering with a browser
Section titled “Rendering with a browser”When a page really needs JavaScript (content built in the browser, infinite scroll, clicks, screenshots, PDFs), install the browser plugin:
pam composer require pushinbr/pam-crawl-browserThe core package then finds it automatically:
use Pam\Crawl\Crawl;
// HTTP first; render only app shells, bot walls and hosts learned to need JavaScript.$page = Crawl::url('https://quotes.toscrape.com/js/')->render()->get();
// Render every page, like Crawl4AI.$page = Crawl::url('https://quotes.toscrape.com/js/')->browser()->get();
var_dump($page->rendered); // true when the HTML came from the browser->render() uses RenderMode::Auto. The plugin drives Lightpanda by default and Chrome when you
ask for screenshots, PDFs or MHTML. Its documentation covers engines,
profiles and every browser option.
The crawler methods that need a browser are part of the core API, so your code stays the same whichever renderer is installed:
| Method | Description |
|---|---|
js(string ...$code) |
Run JavaScript in the page. Return values land in $page->jsResults. |
script(string $c4a, ?string $root = null) |
Run a C4A-Script. |
waitFor(string $condition, float $timeout = 30.0) |
Wait for css:selector, js:() => condition or a bare CSS selector. |
waitUntil(string $event) |
domcontentloaded, load or networkidle. |
scrollFullPage(float $delay = 0.2, ?int $maxSteps = null) |
Scroll to the bottom to trigger lazy loading. |
virtualScroll(string $container, int $count = 10, ...) |
Collect items from virtualized lists. |
screenshot(bool $fullPage = true) |
PNG bytes in $page->screenshot. |
capturePdf() / captureMhtml() |
$page->pdfBytes / $page->mhtml. |
captureNetwork() / captureConsole() |
$page->network / $page->console. |
viewport(int $width, int $height, float $scale = 1.0, bool $mobile = false) |
The browser viewport. |
engine(string $engine) |
chrome, lightpanda or a CDP WebSocket URL. |
magic() |
Hide automation fingerprints and dismiss overlays and consent banners. |
blockResources(string ...$types) |
Block image, media, font, stylesheet, script, xhr or other. |
tab(string $sessionId) |
Keep one browser tab alive across crawls, for multi-step flows. |
Bring your own renderer
Section titled “Bring your own renderer”->render() and ->browser() accept any Pam\Crawl\Render\Renderer. For a remote rendering
service or scraping API, fallback() is often simpler: it receives the URL of a blocked or failed
page and returns HTML (or null):
$crawler = Crawl::urls($urls)->fallback( fn (string $url): ?string => $renderingService->html($url),);C4A-Script
Section titled “C4A-Script”C4A-Script is Crawl4AI’s small language for browser automation: waits, clicks, typing, scrolling, conditions, loops and procedures. PAM Crawl compiles it to the same JavaScript Crawl4AI generates. Compiling needs no browser, so you can validate scripts in tests or CI:
use Pam\Crawl\Script\C4a;
$script = <<<'C4A' # accept cookies if a banner is shown, log in, then load more items SETVAR user = "demo" PROC login SET `#username` $user SET `#password` "secret" CLICK `input[type=submit]` ENDPROC IF (EXISTS `.cookie-banner`) THEN CLICK `.cookie-banner .accept` WAIT `#username` 10 login REPEAT (SCROLL DOWN 500, 3) C4A;
$result = C4a::compile($script);
if ($result->success) { print_r($result->js()); // the generated JavaScript statements} else { echo $result->firstError()?->formattedMessage(); // code, line, column, suggestions}To run a script, pass it to the crawler. With the browser plugin installed it runs in a real headless browser:
$page = Crawl::url('https://quotes.toscrape.com/login')->script($script)->get();C4a::compile() never throws. ->script() throws a Script\CompileError with the same details
when the script does not compile.
The supported commands are GO, RELOAD, BACK, FORWARD, WAIT, CLICK, DOUBLE_CLICK,
RIGHT_CLICK, MOVE, DRAG, SCROLL, TYPE, CLEAR, SET, PRESS, KEY_DOWN, KEY_UP,
EVAL, SETVAR, IF/THEN/ELSE (with EXISTS, NOT and JavaScript conditions), REPEAT,
PROC/ENDPROC and USE "file.c4a", plus # comments. C4a::validate() checks a script and
C4a::compileFile() compiles one from disk.
Next steps
Section titled “Next steps”- Install real rendering with the browser plugin.
- Map hydration data to typed objects in Extraction.
- Compare with Crawl4AI’s browser-first model in Coming from Crawl4AI.
This product includes software developed by UncleCode (https://x.com/unclecode) as part of the Crawl4AI project (https://github.com/unclecode/crawl4ai).