santoku-cdp
View on LuaRocksChrome DevTools Protocol client that drives a Chromium page from Lua, plus a toku-browser shell command
santoku-cdp drives a Chromium browser from Lua over the Chrome DevTools Protocol. It attaches to a page, navigates, evaluates JavaScript, waits for an element and takes screenshots. The toku-browser command does the same from a shell.
Details
- santoku-cdp speaks the protocol through santoku-socket's WebSocket client, so it needs native sockets. It runs in CLIs and scripts but not in this page, so the examples are shown for reading.
- toku browser reaches the toku-browser command.
- Since santoku-cdp 0.5.0, every wait goes through santoku.system.async. One script drives several pages at once with a task per page: async.spawn each page's steps, then join them with a semaphore.
A browser's DevTools port
santoku-cdp attaches to a browser started with --remote-debugging-port. targets(opts) and version(opts) read the browser's /json/list and /json/version.
$ chromium --headless=new --remote-debugging-port=9222 &
$ toku browser targets
3F2A... page about:blank about:blank
Details
- opts.host defaults to 127.0.0.1, and opts.port defaults to 9222.
- A failed request raises "cdp: GET failed" with the path and status.
- page_target(opts) returns the first page target, or the one that opts.id names.
- page_target raises "cdp: no page target" when no target matches.
Screenshots and element waits
screenshot(s[, opts]) returns PNG bytes of the viewport. wait_for(s, selector[, ms]) waits for a CSS match, and center(s, selector) returns the center of the first match.
local fs = require("santoku.fs")
local page = require("santoku.cdp.page")
local s = page.open({ port = 9222 })
page.navigate(s, "https://santoku.dev/")
page.wait_for(s, "nav a", 5000)
fs.writefile("site.png", page.screenshot(s, { full = true }))
s.close()
Details
- With opts.full, screenshot sizes the capture to the page's content, so the whole page comes back in one image.
- screenshot's opts.ms bounds the capture, 30000 by default.
- wait_for checks for a CSS match every 200 ms while it keeps reading events.
- After ms, 10000 by default, wait_for raises "cdp: no element matches" with the selector.
- center scrolls the first match into view and returns the x and y of its center for santoku.cdp.input.
- center raises the same error as wait_for when nothing matches.
Clicks, keys and touch drags
santoku.cdp.input sends trusted input events, the ones that toku-browser's click, key, text and drag commands send. Pair click with page.center to hit an element.
local page = require("santoku.cdp.page")
local input = require("santoku.cdp.input")
local s = page.open({ port = 9222 })
page.navigate(s, "https://santoku.dev/")
input.click(s, page.center(s, "input"))
input.text(s, "lpeg")
input.key(s, "Enter")
input.drag(s, 300, 400, 300, 100, { steps = 12 })
s.close()
Details
- click(s, x, y[, opts]) moves, presses and releases the mouse at a point.
- click's opts.button is "left" by default, and opts.count sets the click count, 2 for a double click.
- key(s, name[, opts]) presses and releases a named key opts.n times with opts.modifiers, the DevTools bitmask.
- input.keys lists the named keys: Enter, Tab, Backspace, Escape, the arrows, Home, End and Delete. Any other name goes out with key code 0.
- text(s, value) inserts text at the focus as if typed.
- drag(s, x0, y0, x1, y1[, opts]) draws a touch drag in opts.steps moves, 8 by default. It pauses opts.pause ms between moves, 15 by default.
Passkeys and console capture
santoku.cdp.webauthn gives a page a virtual authenticator, so a test can sign in with a passkey. santoku.cdp.auth answers basic-auth challenges, and santoku.cdp.log collects console output.
local cjson = require("cjson")
local page = require("santoku.cdp.page")
local webauthn = require("santoku.cdp.webauthn")
local log = require("santoku.cdp.log")
local s = page.open({ port = 9222 })
local drain = log.watch(s)
local id = webauthn.authenticator(s)
page.navigate(s, "http://localhost:8080/")
page.wait_until(s, "document.body.dataset.signedIn", 10000)
local saved = cjson.encode(webauthn.credentials(s, id))
for _, line in ipairs(drain()) do
print(line)
end
s.close()
Details
- authenticator(s[, opts]) adds an authenticator (CTAP2, internal, resident keys, user verification, PRF) and returns its id.
- credentials(s, id) returns what WebAuthn.getCredentials reports.
- load(s, json[, opts]) adds a fresh authenticator and those credentials back in a later run. It takes { credentials = [...] } or a bare list, and returns the id and the count.
- add(s, id, creds) adds the same decoded table to an authenticator you already have, and returns the count.
- A reloaded passkey signs in, but its PRF output comes back null. So it can't stand in for a PRF-based unlock.
- santoku.cdp.auth.basic(s, url_pattern, user, pass) answers HTTP basic-auth challenges for URLs that match url_pattern, only from the request's own origin.
- auth.basic declines proxy challenges, and returns a function that counts the challenges it answered.
- Event handlers run inside the socket read. So they send with s.send(method, params), which drops the reply, instead of the blocking s.call.
- santoku.cdp.log.watch(s) discards console entries buffered before it ran, enables Runtime and Network, and returns a drain function.
- Each drain call returns the lines collected since the last call: console calls, exceptions, failed requests, HTTP statuses of 400 and up, and WebAuthn credential events.
- toku-browser --passkey-env VAR loads credentials JSON from an environment variable before any command.
- toku-browser --logs prints the drained lines on stderr.
- toku-browser --basic-env USER_VAR,PASS_VAR with --basic-pattern URLPATTERN answers basic auth.
Sessions, calls and events
cdp.page(opts) returns a session on the page's WebSocket, and cdp.connect(url, opts) opens a session on any webSocketDebuggerUrl. call sends one command, on registers an event handler, and wait dispatches events.
local cdp = require("santoku.cdp")
local s = cdp.page({ port = 9222 })
s.on("Network.requestWillBeSent", function (params)
print(params.request.url)
end)
s.call("Network.enable")
s.call("Page.navigate", { url = "https://santoku.dev/" })
s.wait(function () return false end, 2000)
s.close()
Details
- cdp.connect takes any webSocketDebuggerUrl, such as the browser endpoint that version() reports.
- opts.connect_timeout_ms and opts.max_message pass through to the WebSocket client.
- connect raises "cdp: connect failed" with the URL when the handshake fails.
- call(method[, params[, ms]]) sends one command and returns its result. It waits 10000 ms by default.
- call raises "cdp: no reply" with the method and the transport's reason, or "cdp: call failed" with Chrome's message.
- Once the socket has closed, call and send raise "cdp: connection closed" with the method, close code and reason.
- A send that the transport refuses raises "cdp: send failed".
- on(method, fn) registers an event handler, called with the event's params and sessionId.
- wait(fn, ms) reads the socket and dispatches events until fn returns true or ms passes.
- cdp.session(conn) builds the same session over any object with send, wait and close. Its specs use cdp.session to run without a browser.
A tab of your own
cdp.new_page(opts) opens a new about:blank tab through the DevTools /json/new endpoint and returns a session on it. Use it on a shared browser, since page.open attaches to a tab that already exists.
local cdp = require("santoku.cdp")
local page = require("santoku.cdp.page")
local s = page.enable(cdp.new_page({ port = 9222 }))
page.navigate(s, "https://santoku.dev/")
local n = s.loads()
s.call("Page.reload", { ignoreCache = true })
s.wait(function () return s.loads() > n end, 30000)
print(page.eval(s, "document.title"))
s.call("Page.close")
s.close()
Details
- page.enable(s) does what page.open adds to a session. It sends Page.enable and counts load events, which navigate needs.
- s.loads() returns the load count.
- Close the tab with the raw Page.close method, then close the session.
- A reload is Page.reload plus a wait for the count to rise.
toku-browser from a shell
The rock installs a toku-browser command that drives a page from a shell. --host, --port and --id pick the browser and the page.
$ toku browser shot https://santoku.dev/ site.png --full
site.png 1136328 bytes
$ toku browser eval https://santoku.dev/ 'document.links.length'
54
$ toku browser wait 'nav a' --ms 5000
$ toku browser type '#q' komodo
$ toku browser until "document.querySelector('td') && document.querySelector('td').textContent"
"Komodo Island"
Details
- shot and eval load the URL first. Pass - to act on the current page instead.
- eval prints the value as JSON and waits at most 10000 ms for it. eval has no --ms option, so a longer promise needs page.eval(s, expr, ms) from Lua.
- The other commands act on the current page.
- wait waits for a selector, and until waits for a JavaScript condition.
- type types into a selector.
- click clicks a selector or an x,y point, with --right or --double.
- key sends a key, text sends text, and drag draws a touch drag between two points.
- call sends one raw DevTools method.
- toku browser works through toku's command dispatch. santoku-cli 3.3.0 and later run toku-<name> from PATH for any name that isn't a built-in command.
A wasm spec in Chromium
toku-browser run starts its own headless Chromium, runs one wasm spec in it, and exits with the spec's status. toku test --browser uses it as the spec interpreter.
$ TOKU_CHROMIUM=chromium-browser toku browser run build/default-wasm/test/test-browser/test/spec/my_lib.js
$ echo $?
0
$ TOKU_CHROMIUM=chromium TOKU_CHROMIUM_FLAGS=--no-sandbox toku browser run spec.js
Details
- run ignores --host and --port.
- run starts $TOKU_CHROMIUM with a temporary profile and --remote-debugging-port=0, then reads the port that Chromium picked.
- run serves the spec through DevTools request interception at http://localhost/, so no server or fixed port is involved.
- The page relays console output to stdout and errors to stderr.
- The spec is done when its glue has set globalThis.EXITSTATUS and no timer is pending.
- An uncaught error or rejection fails the spec. TOKU_BROWSER_TIMEOUT_MS bounds the spec, 60000 by default.
- After the spec's status is known, run stops only the Chromium it started and deletes the profile.
- TOKU_CHROMIUM_FLAGS adds browser flags.
- santoku.cdp.run.run(spec, opts) does the same from Lua.
Your own headless Chromium since santoku-cdp 0.4.8
santoku.cdp.run.launch(opts) starts the same headless Chromium that run uses, and returns b with b.pid, b.port and b.profile. stop(b) ends that Chromium and deletes the profile.
local cdp = require("santoku.cdp")
local run = require("santoku.cdp.run")
local page = require("santoku.cdp.page")
local b = run.launch({
chromium = "chromium-browser",
port = 19036,
flags = { "--host-resolver-rules=MAP pm.test 127.0.0.1" },
})
local s = page.open({ port = b.port })
page.navigate(s, "http://localhost:18501/")
print(cdp.version({ port = b.port }).Browser)
s.close()
run.stop(b)
Details
- opts.chromium defaults to $TOKU_CHROMIUM.
- launch passes $TOKU_CHROMIUM_FLAGS split on whitespace, which run.env_flags() returns. Then it passes each string in the list opts.flags whole.
- So a value with spaces, such as --host-resolver-rules=MAP host 127.0.0.1, works. A flag the machine needs, such as --no-sandbox, stays on.
- run(spec, opts) takes the same opts.flags and opts.port.
- Without opts.port, each launch picks its own DevTools port, so two launches never share one.
- opts.port asks for a fixed port. launch raises when something already answers there, and otherwise waits until Chromium answers on it.
- launch fails when Chromium exits or opens no port within opts.start_ms, 30000 by default.
- On that failure, launch writes the Chromium log tail to opts.err, stops what it started and raises.
- stop(b) waits up to 10 s for Chromium to exit. A second stop does nothing.
- The spec page that run serves loads spec.js inside the body, so a spec can use document.body from its first line.
Examples
Projects that toku init creates with this rock. The examples page shows their files.
- A browser script: A command that loads a page in headless Chromium, reads its title and links, and saves a screenshot.
toku init --example browser my-browser - An offline web app: The web app with its data in sqlite in the browser, synced to the server, and a service worker so it boots offline.
toku init --example pwa my-app - A web app: A WebAssembly client and an OpenResty server in one repository, with the data in sqlite on the server.
toku init --example web my-app