Skip to Content
ReferencePandaScript

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>.js

The 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 own TypeError: Converting circular structure to JSON instead, 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.

These methods bring a page into the browser, or save a URL to a file.

MethodCallSummary
gotoawait page.goto(url[, { timeout, waitUntil }])Open a URL and keep the page in memory
downloadpage.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.

MethodCallSummary
screenshotpage.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.

MethodCallSummary
evaluatepage.evaluate(script[, { url, timeout, save }])Run JavaScript in the page
extractpage.extract(schema)Extract structured data via a CSS-selector schema
classifypage.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.

MethodCallSummary
clickpage.click(selector)Click an element
fillpage.fill(selector, value)Type text into an input
scrollpage.scroll([{ selector, x, y }])Scroll the page or an element
hoverpage.hover(selector)Hover over an element
presspage.press(selector, key)Press a keyboard key
selectOptionpage.selectOption(selector, value)Select an option in a dropdown
setCheckedpage.setChecked(selector[, checked])Check or uncheck a box
acceptCookiespage.acceptCookies([{ prefer, selectors }])Dismiss a cookie consent banner
loginpage.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.

MethodCallSummary
waitForSelectorpage.waitForSelector(selector[, { timeout }])Wait for an element to appear
waitForScriptpage.waitForScript(script[, { timeout }])Wait until a JS expression is truthy
waitForStatepage.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.

MethodCallSummary
callPageToolpage.callPageTool([{ name, arguments }])Call one of the page’s WebMCP tools

Page lifecycle

MethodCallSummary
closepage.close()Stales the handle, so later calls on it fail. The page itself is reclaimed on the next goto or at script end.

Console

MethodWrites to
console.debugstdout
console.errorstderr
console.infostdout
console.logstdout
console.warnstderr

Load states

The states waitForState and goto’s waitUntil accept:

stateResolves 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 valueMeaningComment
"<selector>"Text of the first matching element, or null
""Text of the element currently matchedOnly inside a fields block
["<selector>"]Text of all matching elementsOnly the first element is read, so ["a", "b"] extracts "a" and silently drops "b"
{ selector: "<selector>", attr: "<name>" }Attribute from the first matchhref 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 elementFields accept any shape above, so arrays nest for per-item sub-lists
[{ selector: "<selector>", limit: N }]At most N matchesObject-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:

SchemaResult
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 missingThrows 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
MethodReturnsComment
gotoThe same page object it was called onResolves 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.
closeNothing
downloadsaved <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.
extractAn object or an array, shaped by the schemaSchema forms are listed below.
evaluateA promise of the page value as a string, JSON-encoded when it is an object or arrayurl navigates before running the script, and timeout bounds that navigation, not the script.
classifyA 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).
screenshotSaved <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).
clickClicked element (<target>)
fillFilled element (<target>) with "<value>"
hoverHovered element (<target>)
pressPressed key '<key>'A null selector presses on document.activeElement.
selectOptionSelected option '<value>' (<target>)
setCheckedSet element (<target>) to checked or to uncheckedchecked defaults to true.
scrollScrolled 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.
acceptCookiesAn 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).
loginAn 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).
waitForSelectorElement 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.
waitForScriptScript returned truthy.Same default-timeout rule as waitForSelector. Re-evaluates the script in the page context until it returns truthy.
waitForStatePage reached <state>.Takes one of the load states. timeout defaults to 5000ms.
callPageToolThe tool’s result as a string: the text of an MCP-style content array, or JSON for any other valueA 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.
getCookiesAn array of cookie objects (name, value, domain, path, expires, secure, httpOnly, sameSite), empty when none matchA 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:

ErrorMeaning
Page must be called with newPage(...) 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 closedA method ran on a fresh new Page(), or on a closed page, before await page.goto(url).
page handle is no longer validA 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 definedYou tried to use browser DOM APIs in the agent context. Use extract(...) or page evaluate(...).
ReferenceError: require is not definedAgent scripts are not Node.js scripts.
no page loaded - run page.goto(url) firstA page-dependent primitive ran before navigation.
invalid argumentsA 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 elementEvery field in the schema missed. Fix the selectors; an empty page section yields null/[] per field, not this error.
navigation timed outgoto 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.