PandaScript Reference
A PandaScript is a plain JavaScript automation script that Lightpanda runs directly, with no LLM call. Learn the execution model and see complete examples in the PandaScript usage page.
lightpanda run <my_script>.jsThe script context installs two globals, Page and console, and nothing else from the browser toolset. A script creates a page with new Page(), then calls every method below on that page.
Calling methods
Each method links to its browser tool, which lists all its arguments.
Positional and options arguments. Each primitive takes its leading arguments positionally, with an optional trailing options object for the rest. These two calls are equivalent, and the second is the shape /save records into saved scripts:
waitForSelector("#row", { timeout: 2000 })
waitForSelector({ selector: "#row", timeout: 2000 })A null positional omits that argument: press(null, "Enter") presses on document.activeElement (the focused element, or <body> when nothing is focused).
Invalid calls. These throw invalid arguments:
- An option passed as a bare positional:
waitForSelector("#row", 2000). - The same field set both positionally and in the options object:
goto(url, { url: ... }). - An argument that isn’t JSON-serializable:
undefined, a function or a symbol. A cyclic object throws V8’s ownTypeError: Converting circular structure to JSONinstead, since it fails before Lightpanda’s own check runs.
Selectors, not node IDs. Script primitives address elements by CSS selector only. tree, findElement, and nodeDetails hand out backendNodeIds but aren’t installed in the script context, and a raw node ID wouldn’t survive replay anyway. When you’re exploring in the REPL and have a backendNodeId (the leading number on a /tree line, or a /findElement hit), run /nodeDetails backendNodeId=<id> to get a durable CSS selector, then paste that into your script.
Secrets via $LP_* placeholders. String arguments can contain $LP_* placeholders, resolved inside the Lightpanda process. This keeps credentials out of recorded scripts and LLM prompts. Recordings scrub resolved LP_* values back to placeholders.
Navigation and search
These methods bring a page into the browser, or save a URL to a file.
| Method | Call | Summary |
|---|---|---|
goto | await page.goto(url[, { timeout, waitUntil }]) | Open a URL and keep the page in memory |
download | page.download([{ url, path }]) | Fetch a URL with the session’s cookies into a file |
Reading the page
These methods read the loaded page without modifying it.
| Method | Call | Summary |
|---|---|---|
screenshot | page.screenshot([{ path, selector, fullPage, strip, url, timeout }]) | Screenshot of the page or a node |
Data extraction and scripting
These methods return structured results from the loaded page.
| Method | Call | Summary |
|---|---|---|
evaluate | page.evaluate(script[, { url, timeout, save }]) | Run JavaScript in the page |
extract | page.extract(schema) | Extract structured data via a CSS-selector schema |
classify | page.classify(questions[, { selector, presets }]) | Classify page state using semantic questions or presets |
Interacting with the page
These methods dispatch real DOM events on the page.
| Method | Call | Summary |
|---|---|---|
click | page.click(selector) | Click an element |
fill | page.fill(selector, value) | Type text into an input |
scroll | page.scroll([{ selector, x, y }]) | Scroll the page or an element |
hover | page.hover(selector) | Hover over an element |
press | page.press(selector, key) | Press a keyboard key |
selectOption | page.selectOption(selector, value) | Select an option in a dropdown |
setChecked | page.setChecked(selector[, checked]) | Check or uncheck a box |
acceptCookies | page.acceptCookies([{ prefer, selectors }]) | Dismiss a cookie consent banner |
login | page.login([{ password, username, usernameSelector, passwordSelector, submitSelector, nextSelector, decideOnly }]) | Sign in, picking the fields with Jev |
Waiting
These methods block until the page reaches a condition.
| Method | Call | Summary |
|---|---|---|
waitForSelector | page.waitForSelector(selector[, { timeout }]) | Wait for an element to appear |
waitForScript | page.waitForScript(script[, { timeout }]) | Wait until a JS expression is truthy |
waitForState | page.waitForState(state[, { timeout }]) | Wait for the page to reach a load state |
Page tools (WebMCP)
These methods list and call the tools a page registers for agents through WebMCP.
| Method | Call | Summary |
|---|---|---|
callPageTool | page.callPageTool([{ name, arguments }]) | Call one of the page’s WebMCP tools |
Page lifecycle
| Method | Call | Summary |
|---|---|---|
close | page.close() | Stales the handle, so later calls on it fail. The page itself is reclaimed on the next goto or at script end. |
Console
| Method | Writes to |
|---|---|
console.debug | stdout |
console.error | stderr |
console.info | stdout |
console.log | stdout |
console.warn | stderr |
Load states
The states waitForState and goto’s waitUntil accept:
state | Resolves when |
|---|---|
"load" | The load event fires: the frame and all its subresources, including async scripts, have finished loading. |
"domcontentloaded" | The HTML is parsed and deferred scripts have run. Subresources (images, stylesheets, async scripts) may still be loading. |
"networkalmostidle" | At most 2 requests stay in flight for 500 ms straight. |
"networkidle" | Zero requests stay in flight for 500 ms straight. |
"settled" | Experimental. Waits for load, then for the requests and short timers that page-load work started, ignoring intervals, long timeouts, idle callbacks and WebSocket traffic. Resolves at load when load started nothing. |
"done" | The page goes fully idle: no scheduled JavaScript work and no network activity. Every waitForState call eventually resolves to this, even if the requested state is never reached. |
Extraction schema
page.extract(...) takes a schema object mapping output field names to CSS-selector specs. The schema forms are:
| Schema value | Meaning | Comment |
|---|---|---|
"<selector>" | Text of the first matching element, or null | |
"" | Text of the element currently matched | Only inside a fields block |
["<selector>"] | Text of all matching elements | Only the first element is read, so ["a", "b"] extracts "a" and silently drops "b" |
{ selector: "<selector>", attr: "<name>" } | Attribute from the first match | href and src resolve to absolute URLs |
[{ selector: "<selector>", attr: "<name>" }] | Attribute from all matches | |
[{ selector: "<selector>", fields: { ... } }] | Array of records, with fields resolved relative to each matched element | Fields accept any shape above, so arrays nest for per-item sub-lists |
[{ selector: "<selector>", limit: N }] | At most N matches | Object-array form only, the ["<selector>"] shorthand has no equivalent |
Passing the schema. These three calls are equivalent:
page.extract({ title: "h1" });
page.extract({ schema: { title: "h1" } });
page.extract('{ "title": "h1" }');The object form accepts only the schema key, so the REPL’s save option is rejected in scripts.
What you get back. Every extracted value is a string (trimmed text or a raw attribute) or null; parse numbers yourself. The result mirrors the top-level schema:
| Schema | Result |
|---|---|
An object, { title: "h1" } | An object keyed by your fields, even with a single field |
A bare array, [{ selector: "a" }] | The array itself |
| An array field matching nothing | [] |
| Every field in the schema missing | Throws no schema selector matched any element |
Return values
evaluate runs a JavaScript string inside the page, where window and document exist, and extract resolves its schema selectors there too. That code runs in the page, so it cannot see the variables of your agent script. screenshot doesn’t run any page JavaScript; it renders the same computed layout extract and markdown read as a PNG instead of text.
Every interaction reports the page URL, HTTP status and title reached after the action, so a script can tell whether it triggered a navigation, and whether it landed on an error page. A click returns, in full:
Clicked element (selector: a.login). Page url: https://example.com/app, HTTP 200 OK, title: Dashboard| Method | Returns | Comment |
|---|---|---|
goto | The same page object it was called on | Resolves once waitUntil is reached. waitUntil takes the same states as waitForState: load (default, a fast snapshot that skips content rendered by post-load JavaScript), domcontentloaded, networkalmostidle, networkidle, settled, or done. |
close | Nothing | |
download | saved <bytes> bytes (<content type>) to <absolute path> | Any status outside 200-203 throws HTTP <status> <text>; nothing saved. A failed download leaves an existing file at path untouched. |
extract | An object or an array, shaped by the schema | Schema forms are listed below. |
evaluate | A promise of the page value as a string, JSON-encoded when it is an object or array | url navigates before running the script, and timeout bounds that navigation, not the script. |
classify | A string for an array of categories, the one that fits. An object for an object of questions, keyed by the name you gave each one. | In the object, a preset or yes/no question answers with its probability, a choice with the option picked, and a levels question with { score, level, probabilities }. A missing answer is null. Every run needs the decision model, replays included (see below the table to set it up). |
screenshot | Saved <width>x<height> PNG to <path> | path is required in scripts: a script cannot display an inline image, so omitting it throws pass `path`: this client cannot display an inline image. Renders the page, or one scoped node, as a PNG: the text layout Lightpanda computes, not a pixel-accurate rendering (no images, fonts, or CSS colours). |
click | Clicked element (<target>) | |
fill | Filled element (<target>) with "<value>" | |
hover | Hovered element (<target>) | |
press | Pressed key '<key>' | A null selector presses on document.activeElement. |
selectOption | Selected option '<value>' (<target>) | |
setChecked | Set element (<target>) to checked or to unchecked | checked defaults to true. |
scroll | Scrolled window to x: <x>, y: <y>, Scrolled element (<target>) to ..., or Scrolled scroll container (<container>) of element (<target>) to ... | selector scrolls that element’s scroll container (its nearest scrollable ancestor if it isn’t one) instead of the window; an omitted axis keeps its current offset. |
acceptCookies | An object with dismissed, verified and attempts. selectors, control, confidence, consentWall, consentWallAfter, candidates and reason appear when set. | dismissed says a control was clicked, and verified says the page re-read showed the banner gone, so check both. A page with no banner returns dismissed: false and a reason instead of throwing. Pass selectors from an earlier result to click with no model call; otherwise it needs the decision model (see below the table to set it up). |
login | An object with submitted, loggedIn, pressedEnter and calls. usernameSelector, passwordSelector, submitSelector, nextSelector, candidates, loginWall, errorPage and reason appear when set. | A page it can’t sign in on returns submitted: false and a reason instead of throwing, so check loggedIn. Pass the selectors from an earlier result to fill the fields with no model call; otherwise it needs the decision model (see below the table to set it up). |
waitForSelector | Element found. backendNodeId: <id> | timeout defaults to 5000ms once the page has reached load, or 15000ms (the navigation budget plus 5000) if it hasn’t yet. A script cannot act on that ID, since every method takes a CSS selector. |
waitForScript | Script returned truthy. | Same default-timeout rule as waitForSelector. Re-evaluates the script in the page context until it returns truthy. |
waitForState | Page reached <state>. | Takes one of the load states. timeout defaults to 5000ms. |
callPageTool | The tool’s result as a string: the text of an MCP-style content array, or JSON for any other value | A tool that throws or rejects, or returns isError: true, throws its message in the script. If the tool navigates, the string ends with (Navigated to <url>, HTTP <status>, title: <title>). An unknown name throws No WebMCP tool named "<name>" on this page; pageTools lists them. |
getCookies | An array of cookie objects (name, value, domain, path, expires, secure, httpOnly, sameSite), empty when none match | A saved script never records it (--save), but a script you write can call it. |
The decision model behind classify, acceptCookies and login needs TYPESAFE_API_KEY (the default provider), or a Google key (GOOGLE_API_KEY or GEMINI_API_KEY) with LIGHTPANDA_DECISION_PROVIDER=gemini. Without a key, these calls throw <method>: no decision model key is set.
Errors
Primitive failures throw JavaScript exceptions. The complete list:
| Error | Meaning |
|---|---|
Page must be called with new | Page(...) was called without new. Use new Page(). |
extract is not defined (or click, fill, …) | Primitives are methods on the page object, not globals. Use page.extract(...), not a bare extract(...). |
page is not navigated or has been closed | A method ran on a fresh new Page(), or on a closed page, before await page.goto(url). |
page handle is no longer valid | A re-goto on the same page object that failed or timed out: the old frame is torn down before the new navigation’s outcome is known, so a rejected re-navigation leaves the handle bound to a removed frame. A successful re-goto rebinds the same object to the new frame and keeps working; sibling pages from other new Page() calls are unaffected either way. |
ReferenceError: document is not defined | You tried to use browser DOM APIs in the agent context. Use extract(...) or page evaluate(...). |
ReferenceError: require is not defined | Agent scripts are not Node.js scripts. |
no page loaded - run page.goto(url) first | A page-dependent primitive ran before navigation. |
invalid arguments | A primitive received the wrong number or shape of arguments, or a value that stringifies to undefined (like a bare function or symbol). A cyclic object throws a different, native error instead. |
extract: no schema selector matched any element | Every field in the schema missed. Fix the selectors; an empty page section yields null/[] per field, not this error. |
navigation timed out | goto did not finish loading before its timeout. Also navigation failed, navigation cancelled, and navigation abandoned for the other navigation outcomes. |
<tool> failed: <ZigErrorName> | Fallback for any other tool failure, e.g. click failed: NodeNotFound when a selector matches nothing. |