sema-browser 0.1.1
Drive a real browser over CDP: navigate, click, fill, wait, screenshot, and agent-facing page snapshots
Exported declarations from this release. Parameter names and descriptions come directly from its source.
No matching exports. Try a function name or a word from its description.
(browser/close! b)Close the browser and release its process.
View source definition
(define (browser/close! b)
"Close the browser and release its process."
(cdp/close! b))(browser/connect url)Attach to an already-running browser by its devtools address — see cdp/connect.
View source definition
(define (browser/connect url)
"Attach to an already-running browser by its devtools address — see cdp/connect."
(cdp/connect url))(browser/context-page b context-id)Open a new page inside a browser context from browser/new-context!. Pages in the same context share cookies and storage.
View source definition
(define (browser/context-page b context-id)
"Open a new page inside a browser context from browser/new-context!. Pages in the same context share cookies and storage."
(let ((tid (:targetId (cdp/send b "Target.createTarget"
{:url "about:blank" :browserContextId context-id}))))
(init-page (cdp/attach! b tid))))(browser/devices)List the device preset names usable with page/emulate-device!.
View source definition
(define (browser/devices)
"List the device preset names usable with page/emulate-device!."
(keys device-presets))(browser/dispose-context! b context-id)Dispose a browser context, closing its pages and discarding its state.
View source definition
(define (browser/dispose-context! b context-id)
"Dispose a browser context, closing its pages and discarding its state."
(cdp/send b "Target.disposeBrowserContext" {:browserContextId context-id})
nil)(browser/incognito-page b)Open a page in a fresh incognito browser context — isolated cookies and storage, discarded when the browser closes.
View source definition
(define (browser/incognito-page b)
"Open a page in a fresh incognito browser context — isolated cookies and storage, discarded when the browser closes."
(browser/context-page b (browser/new-context! b)))(browser/launch . opts-rest)Launch a browser and return it. Options map: :headless (default #t), :chrome, :args, :user-data-dir — see cdp/launch.
View source definition
(define (browser/launch . opts-rest)
"Launch a browser and return it. Options map: :headless (default #t), :chrome, :args, :user-data-dir — see cdp/launch."
(if (null? opts-rest) (cdp/launch) (cdp/launch (first opts-rest))))(browser/new-context! b)Create an isolated incognito browser context (own cookies and storage) and return its id. Open pages in it with browser/context-page.
View source definition
(define (browser/new-context! b)
"Create an isolated incognito browser context (own cookies and storage) and return its id. Open pages in it with browser/context-page."
(:browserContextId (cdp/send b "Target.createBrowserContext")))(browser/page b)Open a new tab and return a page. The page doubles as a cdp session, so (cdp/send page ...) reaches the whole protocol.
View source definition
(define (browser/page b)
"Open a new tab and return a page. The page doubles as a cdp session, so (cdp/send page ...) reaches the whole protocol."
(init-page (cdp/attach! b (cdp/new-target! b "about:blank"))))(browser/pages b)Attach to every already-open tab and return them as pages, in target order. Useful after browser/connect to drive an existing session.
View source definition
(define (browser/pages b)
"Attach to every already-open tab and return them as pages, in target order. Useful after browser/connect to drive an existing session."
(map (fn (t) (init-page (cdp/attach! b (:targetId t))))
(filter (fn (t) (= "page" (:type t))) (cdp/targets b))))(browser/version b)Return browser version info: :product, :userAgent, :protocolVersion, ...
View source definition
(define (browser/version b)
"Return browser version info: :product, :userAgent, :protocolVersion, ..."
(cdp/version b))(browser/with-page f-or-opts . f-rest)Launch a browser, open a page, call f with it, and always close the browser. (browser/with-page f) or (browser/with-page opts f). Returns f's result.
View source definition
(define (browser/with-page f-or-opts . f-rest)
"Launch a browser, open a page, call f with it, and always close the browser. (browser/with-page f) or (browser/with-page opts f). Returns f's result."
(let* ((opts (if (null? f-rest) {} f-or-opts))
(f (if (null? f-rest) f-or-opts (first f-rest)))
(b (browser/launch opts)))
(try (let ((result (f (browser/page b))))
(browser/close! b)
result)
(catch e
(browser/close! b)
(raise e)))))(page/add-init-script! pg js)Run js in every new document before any page script — polyfills, flags, stubs. Applies from the next navigation. Returns an identifier.
View source definition
(define (page/add-init-script! pg js)
"Run js in every new document before any page script — polyfills, flags, stubs. Applies from the next navigation. Returns an identifier."
(:identifier (cdp/send pg "Page.addScriptToEvaluateOnNewDocument" {:source js})))(page/attr pg sel name . opts-rest)Return an attribute value of the element matching sel (nil if absent), auto-waiting for the element. Options: :timeout ms.
View source definition
(define (page/attr pg sel name . opts-rest)
"Return an attribute value of the element matching sel (nil if absent), auto-waiting for the element. Options: :timeout ms."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(wait-state pg sel :attached (opt-timeout opts))
(page/eval pg (format "(el => el ? el.getAttribute(~a) : null)(~a)"
(json/encode name) (find-js sel)))))(page/authenticate! pg username password)Answer HTTP basic/proxy auth challenges with these credentials. Returns an interceptor id for page/stop-intercept!. Owns the Fetch domain like page/on-request! — the two are mutually exclusive until stopped. A challenge the credentials already failed once is cancelled rather than re-answered, so a wrong password fails instead of looping.
View source definition
(define (page/authenticate! pg username password)
"Answer HTTP basic/proxy auth challenges with these credentials. Returns an interceptor id for page/stop-intercept!. Owns the Fetch domain like page/on-request! — the two are mutually exclusive until stopped. A challenge the credentials already failed once is cancelled rather than re-answered, so a wrong password fails instead of looping."
(cdp/send pg "Fetch.enable" {:handleAuthRequests #t :patterns [{:urlPattern "*"}]})
(let ((answered (mutable-cell/new {}))
(pass-id (cdp/on! pg "Fetch.requestPaused"
(fn (ev)
(try (cdp/send pg "Fetch.continueRequest"
{:requestId (get-in ev [:params :requestId])})
(catch e nil))))))
(let ((auth-id (cdp/on! pg "Fetch.authRequired"
(fn (ev)
(let ((rid (get-in ev [:params :requestId])))
(if (get (mutable-cell/get answered) rid)
(cdp/send pg "Fetch.continueWithAuth"
{:requestId rid
:authChallengeResponse {:response "CancelAuth"}})
(begin
(mutable-cell/set! answered
(assoc (mutable-cell/get answered) rid #t))
(cdp/send pg "Fetch.continueWithAuth"
{:requestId rid
:authChallengeResponse
{:response "ProvideCredentials"
:username username
:password password}}))))))))
(list pass-id auth-id))))(page/back pg)Go back one entry in the page's history, waiting for the load.
View source definition
(define (page/back pg)
"Go back one entry in the page's history, waiting for the load."
(history-step pg -1))(page/block! pg patterns)Block every request whose URL contains any of the given substrings; everything else continues. Returns an interceptor id for page/stop-intercept!.
View source definition
(define (page/block! pg patterns)
"Block every request whose URL contains any of the given substrings; everything else continues. Returns an interceptor id for page/stop-intercept!."
(let ((pats (if (string? patterns) (list patterns) patterns)))
(page/on-request! pg
(fn (req)
(if (first (filter (fn (p) (string/contains? (:url req) p)) pats))
:abort
:continue)))))(page/bounding-box pg sel . opts-rest)Return the element's bounding box in main-viewport coordinates: {:x :y :width :height}. Auto-waits for the element to be visible. Options: :timeout ms.
View source definition
(define (page/bounding-box pg sel . opts-rest)
"Return the element's bounding box in main-viewport coordinates: {:x :y :width :height}. Auto-waits for the element to be visible. Options: :timeout ms."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(wait-state pg sel :visible (opt-timeout opts))
(let ((oid (resolve-object pg sel)))
(when (nil? oid)
(error (format "page/bounding-box: element ~a disappeared" sel)))
(with-object pg oid
(fn (o)
(call-on pg o
"function(){ this.scrollIntoView({block:'center', inline:'center'}); }")
(quads->box (:quads (cdp/send pg "DOM.getContentQuads" {:objectId o}))))))))(page/check pg sel . opts-rest)Ensure the checkbox/radio matching sel is checked (clicks only when needed). Options: :timeout ms.
View source definition
(define (page/check pg sel . opts-rest)
"Ensure the checkbox/radio matching sel is checked (clicks only when needed). Options: :timeout ms."
(set-checked pg sel #t (if (null? opts-rest) {} (first opts-rest))))(page/clear-console! pg)Drop the recorded console messages and page errors.
View source definition
(define (page/clear-console! pg)
"Drop the recorded console messages and page errors."
(cdp/clear-events! pg "Runtime.consoleAPICalled")
(cdp/clear-events! pg "Runtime.exceptionThrown")
nil)(page/clear-cookies! pg)Delete all browser cookies.
View source definition
(define (page/clear-cookies! pg)
"Delete all browser cookies."
(cdp/send pg "Network.clearBrowserCookies")
nil)(page/click pg sel . opts-rest)Click the element matching sel with a real mouse event, auto-waiting until it is visible and enabled. Options: :timeout ms, :button (:left default, :right, :middle), :click-count, :modifiers (["Shift" "Meta" ...]).
View source definition
(define (page/click pg sel . opts-rest)
"Click the element matching sel with a real mouse event, auto-waiting until it is visible and enabled. Options: :timeout ms, :button (:left default, :right, :middle), :click-count, :modifiers ([\"Shift\" \"Meta\" ...])."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(with-object pg (actionable-object pg sel (opt-timeout opts))
(fn (oid) (click-object pg oid opts)))))(page/click-ref pg ref)Click the element behind a [ref=eNNN] handle from page/snapshot.
View source definition
(define (page/click-ref pg ref)
"Click the element behind a [ref=eNNN] handle from page/snapshot."
(with-object pg (ref-object pg ref) (fn (oid) (click-object pg oid {}))))(page/clipboard-read pg)Read the clipboard's text (grants the permission). Requires a secure context — localhost or https, not data: URLs.
View source definition
(define (page/clipboard-read pg)
"Read the clipboard's text (grants the permission). Requires a secure context — localhost or https, not data: URLs."
(grant-clipboard! pg)
(page/eval pg "navigator.clipboard.readText()"))(page/clipboard-write! pg text)Write text to the clipboard (grants the permission). Requires a secure context — localhost or https, not data: URLs.
View source definition
(define (page/clipboard-write! pg text)
"Write text to the clipboard (grants the permission). Requires a secure context — localhost or https, not data: URLs."
(grant-clipboard! pg)
(page/eval pg (format "navigator.clipboard.writeText(~a).then(() => true)"
(json/encode text)))
nil)(page/close! pg)Close the page's tab.
View source definition
(define (page/close! pg)
"Close the page's tab."
(cdp/send (:conn pg) "Target.closeTarget" {:targetId (:target-id pg)})
nil)(page/console pg)Return console messages and uncaught errors recorded since page/track-console!, as {:type :text}, oldest first.
View source definition
(define (page/console pg)
"Return console messages and uncaught errors recorded since page/track-console!, as {:type :text}, oldest first."
(filter (fn (m) (not (nil? m)))
(map console-event->map (cdp/events pg))))(page/cookies pg)Return the cookies visible to the page as maps with :name, :value, :domain, :path, :expires, :httpOnly, :secure.
View source definition
(define (page/cookies pg)
"Return the cookies visible to the page as maps with :name, :value, :domain, :path, :expires, :httpOnly, :secure."
(:cookies (cdp/send pg "Network.getCookies")))(page/count pg sel)Return how many elements match sel right now — does not wait.
View source definition
(define (page/count pg sel)
"Return how many elements match sel right now — does not wait."
(page/eval pg (format "(~a).length" (find-all-js sel))))(page/dblclick pg sel . opts-rest)Double-click the element matching sel. Options as page/click.
View source definition
(define (page/dblclick pg sel . opts-rest)
"Double-click the element matching sel. Options as page/click."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(with-object pg (actionable-object pg sel (opt-timeout opts))
(fn (oid) (click-object pg oid (assoc opts :click-count 2))))))(page/downloads-to! pg dir)Send this browser's downloads to dir (created if missing) and enable download events for page/wait-for-download.
View source definition
(define (page/downloads-to! pg dir)
"Send this browser's downloads to dir (created if missing) and enable download events for page/wait-for-download."
(file/mkdir dir)
(cdp/send (:conn pg) "Browser.setDownloadBehavior"
{:behavior "allow" :downloadPath dir :eventsEnabled #t})
(mutable-cell/set! download-dir dir)
nil)(page/drag pg from-sel to-sel . opts-rest)Drag from one element's center to another's with real mouse events (press, move in steps, release). Options: :steps (default 10), :timeout ms.
View source definition
(define (page/drag pg from-sel to-sel . opts-rest)
"Drag from one element's center to another's with real mouse events (press, move in steps, release). Options: :steps (default 10), :timeout ms."
(let* ((opts (if (null? opts-rest) {} (first opts-rest)))
(steps (get opts :steps 10))
(from (with-object pg (actionable-object pg from-sel (opt-timeout opts))
(fn (oid) (element-center pg oid))))
(to (with-object pg (actionable-object pg to-sel (opt-timeout opts))
(fn (oid) (element-center pg oid)))))
(cdp/send pg "Input.dispatchMouseEvent"
{:type "mouseMoved" :x (:x from) :y (:y from)})
(cdp/send pg "Input.dispatchMouseEvent"
{:type "mousePressed" :x (:x from) :y (:y from)
:button "left" :clickCount 1})
(let loop ((i 1))
(when (<= i steps)
(cdp/send pg "Input.dispatchMouseEvent"
{:type "mouseMoved" :button "left"
:x (+ (:x from) (* (- (:x to) (:x from)) (/ i steps)))
:y (+ (:y from) (* (- (:y to) (:y from)) (/ i steps)))})
(loop (+ i 1))))
(cdp/send pg "Input.dispatchMouseEvent"
{:type "mouseReleased" :x (:x to) :y (:y to)
:button "left" :clickCount 1})
nil))(page/emulate-device! pg name)Emulate a device preset by name — viewport, scale, mobile flag, and User-Agent. See browser/devices for the names.
View source definition
(define (page/emulate-device! pg name)
"Emulate a device preset by name — viewport, scale, mobile flag, and User-Agent. See browser/devices for the names."
(let ((d (get device-presets name)))
(when (nil? d)
(error (format "page/emulate-device!: unknown device ~a — known: ~a"
name (string/join (keys device-presets) ", "))))
(page/set-viewport! pg (:width d) (:height d)
{:scale (:scale d) :mobile (:mobile d)})
(page/set-user-agent! pg (:ua d))
nil))(page/eval pg js)Evaluate a JS expression in the page (promises awaited) and return its value as data. Raises if the page throws.
View source definition
(define (page/eval pg js)
"Evaluate a JS expression in the page (promises awaited) and return its value as data. Raises if the page throws."
(:value (raw-eval pg js #t)))(page/eval-in-frame pg frame-id js)Evaluate a JS expression inside a specific frame by id (see page/frames) and return its value. Runs in an isolated world, so it sees the frame's DOM but not its page-script variables.
View source definition
(define (page/eval-in-frame pg frame-id js)
"Evaluate a JS expression inside a specific frame by id (see page/frames) and return its value. Runs in an isolated world, so it sees the frame's DOM but not its page-script variables."
(page/eval (assoc pg :frame-id frame-id :ctx-cell (mutable-cell/new nil)) js))(page/exists? pg sel)Return whether any element matches sel right now — does not wait.
View source definition
(define (page/exists? pg sel)
"Return whether any element matches sel right now — does not wait."
(> (page/count pg sel) 0))(page/fill pg sel text . opts-rest)Focus the element matching sel and replace its contents with text (real text-input events). Works on inputs, textareas, and contenteditable. Options: :timeout ms.
View source definition
(define (page/fill pg sel text . opts-rest)
"Focus the element matching sel and replace its contents with text (real text-input events). Works on inputs, textareas, and contenteditable. Options: :timeout ms."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(with-object pg (actionable-object pg sel (opt-timeout opts))
(fn (oid) (fill-object pg oid text)))))(page/fill-ref pg ref text)Fill the element behind a [ref=eNNN] handle from page/snapshot.
View source definition
(define (page/fill-ref pg ref text)
"Fill the element behind a [ref=eNNN] handle from page/snapshot."
(with-object pg (ref-object pg ref) (fn (oid) (fill-object pg oid text)))))(page/focus pg sel . opts-rest)Focus the element matching sel. Options: :timeout ms.
View source definition
(define (page/focus pg sel . opts-rest)
"Focus the element matching sel. Options: :timeout ms."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(with-object pg (actionable-object pg sel (opt-timeout opts))
(fn (oid) (call-on pg oid "function(){ this.focus(); }")))))(page/forward pg)Go forward one entry in the page's history, waiting for the load.
View source definition
(define (page/forward pg)
"Go forward one entry in the page's history, waiting for the load."
(history-step pg 1))(page/frame pg spec)Return a frame handle for the child frame whose id, name, or URL (substring) matches spec. The handle works like a page for selector actions, page/eval, page/text, page/click, page/fill, page/snapshot, refs, ... — all scoped to that frame. Cross-origin frames that Chrome isolates into their own process (OOPIFs) are not in this page's tree; adopt those via browser/pages.
View source definition
(define (page/frame pg spec)
"Return a frame handle for the child frame whose id, name, or URL (substring) matches spec. The handle works like a page for selector actions, page/eval, page/text, page/click, page/fill, page/snapshot, refs, ... — all scoped to that frame. Cross-origin frames that Chrome isolates into their own process (OOPIFs) are not in this page's tree; adopt those via browser/pages."
(let ((match (first (filter (fn (f) (and (:parent f) (frame-matches? f spec)))
(page/frames pg)))))
(when (nil? match)
(error (format "page/frame: no child frame matching ~a — frames: ~a"
spec (map (fn (f) (:url f)) (page/frames pg)))))
(assoc pg :frame-id (:id match) :ctx-cell (mutable-cell/new nil))))(page/frames pg)List the page's frames as maps with :id, :url, :name, :parent (nil for the main frame).
View source definition
(define (page/frames pg)
"List the page's frames as maps with :id, :url, :name, :parent (nil for the main frame)."
(flatten-frames (:frameTree (cdp/send pg "Page.getFrameTree")) nil (list)))(page/goto pg url . opts-rest)Navigate to url and wait for it. Options: :timeout ms (default 30000), :wait-until (:load default, :domcontentloaded, or :networkidle — no in-flight requests for 500ms).
View source definition
(define (page/goto pg url . opts-rest)
"Navigate to url and wait for it. Options: :timeout ms (default 30000), :wait-until (:load default, :domcontentloaded, or :networkidle — no in-flight requests for 500ms)."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(when (= (get opts :wait-until :load) :networkidle)
(ensure-network-counter! pg))
(clear-nav-events! pg)
(let ((r (cdp/send pg "Page.navigate" {:url url})))
(when (:errorText r)
(error (format "page/goto: navigation to ~a failed — ~a" url (:errorText r))))
;; A same-document navigation (e.g. "#anchor") has no loaderId and
;; fires no load event — there is nothing to wait for.
(when (:loaderId r)
(wait-navigated pg (get opts :wait-until :load) (opt-timeout opts)))
nil)))(page/hover pg sel . opts-rest)Move the mouse over the element matching sel (fires mouseover/mouseenter). Options: :timeout ms.
View source definition
(define (page/hover pg sel . opts-rest)
"Move the mouse over the element matching sel (fires mouseover/mouseenter). Options: :timeout ms."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(with-object pg (actionable-object pg sel (opt-timeout opts))
(fn (oid)
(let ((p (element-center pg oid)))
(cdp/send pg "Input.dispatchMouseEvent"
{:type "mouseMoved" :x (:x p) :y (:y p)})
nil)))))(page/html pg)Return the page's full HTML (document.documentElement.outerHTML).
View source definition
(define (page/html pg)
"Return the page's full HTML (document.documentElement.outerHTML)."
(page/eval pg "document.documentElement.outerHTML"))(page/on-dialog! pg action . prompt-rest)Auto-respond to alert/confirm/prompt dialogs: action is :accept or :dismiss, with an optional prompt-text answer for prompt(). Registers a handler; returns its id (cdp/off! to remove). Without a handler an open dialog blocks the page's JS.
View source definition
(define (page/on-dialog! pg action . prompt-rest)
"Auto-respond to alert/confirm/prompt dialogs: action is :accept or :dismiss, with an optional prompt-text answer for prompt(). Registers a handler; returns its id (cdp/off! to remove). Without a handler an open dialog blocks the page's JS."
(let ((accept (= action :accept))
(prompt-text (if (null? prompt-rest) nil (first prompt-rest))))
(cdp/on! pg "Page.javascriptDialogOpening"
(fn (ev)
(cdp/send pg "Page.handleJavaScriptDialog"
(if prompt-text
{:accept accept :promptText prompt-text}
{:accept accept}))))))(page/on-request! pg handler)Intercept every request the page makes. The handler receives {:url :method :resource-type :headers :request-id} and returns :continue (or nil) to let it through, :abort to block it, {:fulfill {:status :headers :body}} to answer it without the network, or {:continue {:url :method :headers :post-data}} to rewrite it. Returns an interceptor id for page/stop-intercept!. One interceptor per page — stop the old one first.
View source definition
(define (page/on-request! pg handler)
"Intercept every request the page makes. The handler receives {:url :method :resource-type :headers :request-id} and returns :continue (or nil) to let it through, :abort to block it, {:fulfill {:status :headers :body}} to answer it without the network, or {:continue {:url :method :headers :post-data}} to rewrite it. Returns an interceptor id for page/stop-intercept!. One interceptor per page — stop the old one first."
(cdp/send pg "Fetch.enable" {:patterns [{:urlPattern "*"}]})
(cdp/on! pg "Fetch.requestPaused"
(fn (ev)
(let* ((p (:params ev))
(req {:request-id (:requestId p)
:url (get-in p [:request :url])
:method (get-in p [:request :method])
:headers (get-in p [:request :headers])
:resource-type (:resourceType p)}))
;; A handler error must not leave the request hanging forever.
(try (respond-to-request! pg (:requestId p) (handler req))
(catch e
(try (cdp/send pg "Fetch.continueRequest"
{:requestId (:requestId p)})
(catch e2 nil))
(raise e)))))))(page/pdf pg . opts-rest)Print the page to PDF (headless only). Returns the bytes, or writes to :path and returns the path. Options: :path, :landscape #t, :scale (0.1-2), :page-ranges ("1-3").
View source definition
(define (page/pdf pg . opts-rest)
"Print the page to PDF (headless only). Returns the bytes, or writes to :path and returns the path. Options: :path, :landscape #t, :scale (0.1-2), :page-ranges (\"1-3\")."
(let* ((opts (if (null? opts-rest) {} (first opts-rest)))
(params (foldl (fn (m kv)
(if (nil? (first (rest kv))) m (apply assoc m kv)))
{:landscape (get opts :landscape #f)}
(list (list :scale (get opts :scale))
(list :pageRanges (get opts :page-ranges)))))
(bytes (base64/decode-bytes (:data (cdp/send pg "Page.printToPDF" params)))))
(if (get opts :path)
(begin (file/write-bytes (get opts :path) bytes) (get opts :path))
bytes)))(page/press pg sel key . opts-rest)Focus the element matching sel and press a key or chord: "Enter", "Tab", "Escape", arrows, any single character, or with modifiers ("Control+a", "Meta+Shift+r"). Options: :timeout ms.
View source definition
(define (page/press pg sel key . opts-rest)
"Focus the element matching sel and press a key or chord: \"Enter\", \"Tab\", \"Escape\", arrows, any single character, or with modifiers (\"Control+a\", \"Meta+Shift+r\"). Options: :timeout ms."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(with-object pg (actionable-object pg sel (opt-timeout opts))
(fn (oid) (call-on pg oid "function(){ this.focus(); }")))
(dispatch-key pg key)))(page/reload pg . opts-rest)Reload the page and wait for it. Options: :ignore-cache #t for a hard reload, :timeout ms, :wait-until (as page/goto).
View source definition
(define (page/reload pg . opts-rest)
"Reload the page and wait for it. Options: :ignore-cache #t for a hard reload, :timeout ms, :wait-until (as page/goto)."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(when (= (get opts :wait-until :load) :networkidle)
(ensure-network-counter! pg))
(clear-nav-events! pg)
(cdp/send pg "Page.reload" {:ignoreCache (get opts :ignore-cache #f)})
(wait-navigated pg (get opts :wait-until :load) (opt-timeout opts))
nil))(page/requests pg)Return the responses recorded since page/track-network! as maps with :url, :status, :mime-type, :type, :request-id — oldest first.
View source definition
(define (page/requests pg)
"Return the responses recorded since page/track-network! as maps with :url, :status, :mime-type, :type, :request-id — oldest first."
(map response-event->map
(filter (fn (ev) (= "Network.responseReceived" (:method ev)))
(cdp/events pg))))(page/response-body pg request-id)Return the body of a recorded response by its :request-id (from page/requests or page/wait-for-response). Text bodies come back as a string, binary ones as a bytevector. Requires page/track-network!, and the body must still be held by the browser (it is dropped on navigation). Retries briefly while the response is still streaming.
View source definition
(define (page/response-body pg request-id)
"Return the body of a recorded response by its :request-id (from page/requests or page/wait-for-response). Text bodies come back as a string, binary ones as a bytevector. Requires page/track-network!, and the body must still be held by the browser (it is dropped on navigation). Retries briefly while the response is still streaming."
;; responseReceived fires before the body finishes loading — retry until
;; loadingFinished has landed (bounded, then surface the real error).
(let loop ((tries 0))
(let ((r (try (cdp/send pg "Network.getResponseBody" {:requestId request-id})
(catch e
(if (and (< tries 20)
(string/contains? (:message e) "No data found"))
:retry
(raise e))))))
(if (= r :retry)
(begin (cdp/pump pg 100) (loop (+ tries 1)))
(if (:base64Encoded r)
(base64/decode-bytes (:body r))
(:body r))))))(page/screenshot pg . opts-rest)Capture a screenshot as PNG bytes. Options: :path (write to file and return the path instead), :format ("png" default, "jpeg", "webp"), :quality (0-100, jpeg/webp), :full-page (capture beyond the viewport), :selector (capture just that element).
View source definition
(define (page/screenshot pg . opts-rest)
"Capture a screenshot as PNG bytes. Options: :path (write to file and return the path instead), :format (\"png\" default, \"jpeg\", \"webp\"), :quality (0-100, jpeg/webp), :full-page (capture beyond the viewport), :selector (capture just that element)."
(let* ((opts (if (null? opts-rest) {} (first opts-rest)))
(params (assoc (if (get opts :quality)
{:quality (get opts :quality)}
{})
:format (get opts :format "png")
:captureBeyondViewport (get opts :full-page #f)))
(params (if (get opts :selector)
(assoc params :clip
(assoc (page/bounding-box pg (get opts :selector)
{:timeout (opt-timeout opts)})
:scale 1))
params))
(r (cdp/send pg "Page.captureScreenshot" params))
(bytes (base64/decode-bytes (:data r))))
(if (get opts :path)
(begin (file/write-bytes (get opts :path) bytes) (get opts :path))
bytes)))(page/scroll pg dx dy . opts-rest)Scroll with a mouse-wheel event: positive dy scrolls down. Options: :selector (wheel over that element instead of the viewport center), :timeout ms.
View source definition
(define (page/scroll pg dx dy . opts-rest)
"Scroll with a mouse-wheel event: positive dy scrolls down. Options: :selector (wheel over that element instead of the viewport center), :timeout ms."
(let* ((opts (if (null? opts-rest) {} (first opts-rest)))
(p (if (get opts :selector)
(with-object pg (actionable-object pg (get opts :selector)
(opt-timeout opts))
(fn (oid) (element-center pg oid)))
(page/eval pg "({x: innerWidth/2, y: innerHeight/2})"))))
(cdp/send pg "Input.dispatchMouseEvent"
{:type "mouseWheel" :x (:x p) :y (:y p) :deltaX dx :deltaY dy})
nil))(page/select pg sel value . opts-rest)Set a <select> and fire input/change events. `value` is an option value string, a list of values (multi-select), or {:label "visible text"}. Non-select elements get their value assigned directly. Options: :timeout ms.
View source definition
(define (page/select pg sel value . opts-rest)
"Set a <select> and fire input/change events. `value` is an option value string, a list of values (multi-select), or {:label \"visible text\"}. Non-select elements get their value assigned directly. Options: :timeout ms."
(let* ((opts (if (null? opts-rest) {} (first opts-rest)))
(spec (cond ((string? value) {:values (list value)})
((map? value)
(if (:label value)
{:label (:label value)}
(error "page/select: map value must be {:label \"...\"}")))
(else {:values value}))))
(with-object pg (actionable-object pg sel (opt-timeout opts))
(fn (oid)
(call-on pg oid
(format "function(){ const spec = ~a;
if (this.options) {
for (const o of this.options)
o.selected = spec.label != null
? o.text.trim() === spec.label
: spec.values.includes(o.value);
} else {
this.value = spec.values ? spec.values[0] : spec.label;
}
this.dispatchEvent(new Event('input', {bubbles:true}));
this.dispatchEvent(new Event('change', {bubbles:true})); }"
(json/encode spec)))))
nil))(page/set-content pg html)Replace the page's document with the given HTML string.
View source definition
(define (page/set-content pg html)
"Replace the page's document with the given HTML string."
(cdp/send pg "Page.setDocumentContent" {:frameId (main-frame-id pg) :html html})
nil)(page/set-cookie! pg cookie)Set one cookie. Map keys: :name and :value (required), plus :url or :domain, :path, :expires (unix seconds), :httpOnly, :secure, :sameSite. Raises when the browser rejects it.
View source definition
(define (page/set-cookie! pg cookie)
"Set one cookie. Map keys: :name and :value (required), plus :url or :domain, :path, :expires (unix seconds), :httpOnly, :secure, :sameSite. Raises when the browser rejects it."
(when (or (nil? (:name cookie)) (nil? (:value cookie)))
(error "page/set-cookie!: cookie needs :name and :value"))
(let ((c (if (or (:url cookie) (:domain cookie))
cookie
(assoc cookie :url (page/url pg)))))
(when (not (:success (cdp/send pg "Network.setCookie" c)))
(error (format "page/set-cookie!: browser rejected cookie ~a" (:name cookie))))
nil))(page/set-cpu-throttle! pg rate)Slow the page's CPU by a factor (2 = half speed). 1 restores full speed.
View source definition
(define (page/set-cpu-throttle! pg rate)
"Slow the page's CPU by a factor (2 = half speed). 1 restores full speed."
(cdp/send pg "Emulation.setCPUThrottlingRate" {:rate rate})
nil)(page/set-geolocation! pg latitude longitude . opts-rest)Override geolocation (and grant the permission). Options: :accuracy meters (default 1).
View source definition
(define (page/set-geolocation! pg latitude longitude . opts-rest)
"Override geolocation (and grant the permission). Options: :accuracy meters (default 1)."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(cdp/send (:conn pg) "Browser.grantPermissions" {:permissions ["geolocation"]})
(cdp/send pg "Emulation.setGeolocationOverride"
{:latitude latitude :longitude longitude
:accuracy (get opts :accuracy 1)})
nil))(page/set-media! pg opts)Emulate media features: {:color-scheme "dark"|"light"} for prefers-color-scheme, {:media "print"} for print styles, {:reduced-motion "reduce"}. Pass {} to reset.
View source definition
(define (page/set-media! pg opts)
"Emulate media features: {:color-scheme \"dark\"|\"light\"} for prefers-color-scheme, {:media \"print\"} for print styles, {:reduced-motion \"reduce\"}. Pass {} to reset."
(let ((features (append
(if (:color-scheme opts)
(list {:name "prefers-color-scheme" :value (:color-scheme opts)})
(list))
(if (:reduced-motion opts)
(list {:name "prefers-reduced-motion" :value (:reduced-motion opts)})
(list)))))
(cdp/send pg "Emulation.setEmulatedMedia"
{:media (get opts :media "") :features features})
nil))(page/set-offline! pg offline)Emulate being offline (#t) or restore connectivity (#f).
View source definition
(define (page/set-offline! pg offline)
"Emulate being offline (#t) or restore connectivity (#f)."
(cdp/send pg "Network.enable")
(cdp/send pg "Network.emulateNetworkConditions"
{:offline offline :latency 0
:downloadThroughput -1 :uploadThroughput -1})
nil)(page/set-timezone! pg timezone-id)Override the page's timezone, e.g. "Europe/Oslo" or "America/New_York".
View source definition
(define (page/set-timezone! pg timezone-id)
"Override the page's timezone, e.g. \"Europe/Oslo\" or \"America/New_York\"."
(cdp/send pg "Emulation.setTimezoneOverride" {:timezoneId timezone-id})
nil)(page/set-user-agent! pg ua)Override the page's User-Agent string for subsequent requests.
View source definition
(define (page/set-user-agent! pg ua)
"Override the page's User-Agent string for subsequent requests."
(cdp/send pg "Emulation.setUserAgentOverride" {:userAgent ua})
nil)(page/set-viewport! pg width height . opts-rest)Emulate a viewport of width x height CSS pixels. Options: :scale (deviceScaleFactor, default 1), :mobile #t.
View source definition
(define (page/set-viewport! pg width height . opts-rest)
"Emulate a viewport of width x height CSS pixels. Options: :scale (deviceScaleFactor, default 1), :mobile #t."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(cdp/send pg "Emulation.setDeviceMetricsOverride"
{:width width :height height
:deviceScaleFactor (get opts :scale 1)
:mobile (get opts :mobile #f)})
nil))(page/snapshot pg)Render the page's accessibility tree as compact text, one node per line with a [ref=eNNN] handle usable with page/click-ref and page/fill-ref. On a frame handle, renders that frame's tree.
View source definition
(define (page/snapshot pg)
"Render the page's accessibility tree as compact text, one node per line with a [ref=eNNN] handle usable with page/click-ref and page/fill-ref. On a frame handle, renders that frame's tree."
(cdp/send pg "Accessibility.enable")
(let* ((nodes (:nodes (cdp/send pg "Accessibility.getFullAXTree"
(if (:frame-id pg)
{:frameId (:frame-id pg)}
{}))))
(by-id (foldl (fn (m n) (assoc m (:nodeId n) n)) {} nodes)))
(if (null? nodes)
""
(string/join (render-ax by-id (first nodes) 0 "" (list)) "\n"))))(page/start-js-coverage! pg)Start collecting JS coverage; navigate/run the code, then read it with page/stop-js-coverage.
View source definition
(define (page/start-js-coverage! pg)
"Start collecting JS coverage; navigate/run the code, then read it with page/stop-js-coverage."
(cdp/send pg "Profiler.enable")
(cdp/send pg "Profiler.startPreciseCoverage" {:callCount #f :detailed #f})
nil)(page/start-screencast! pg dir)Record the page as numbered PNG frames into dir (created if missing) until page/stop-screencast!. Frames arrive while commands run — use (cdp/pump pg ms) to capture during idle stretches. Returns a handle for page/stop-screencast!.
View source definition
(define (page/start-screencast! pg dir)
"Record the page as numbered PNG frames into dir (created if missing) until page/stop-screencast!. Frames arrive while commands run — use (cdp/pump pg ms) to capture during idle stretches. Returns a handle for page/stop-screencast!."
(file/mkdir dir)
(let* ((counter (mutable-cell/new 0))
(hid (cdp/on! pg "Page.screencastFrame"
(fn (ev)
(let ((n (mutable-cell/get counter)))
(mutable-cell/set! counter (+ n 1))
(file/write-bytes
(format "~a/frame-~a.png" dir (+ 100000 n))
(base64/decode-bytes (get-in ev [:params :data]))))
(cdp/send pg "Page.screencastFrameAck"
{:sessionId (get-in ev [:params :sessionId])})))))
(cdp/send pg "Page.startScreencast" {:format "png"})
{:handler-id hid :dir dir}))(page/stop-intercept! pg interceptor-id)Remove an interceptor from page/on-request!, page/block!, or page/authenticate! (a single id or a list of ids) and stop intercepting.
View source definition
(define (page/stop-intercept! pg interceptor-id)
"Remove an interceptor from page/on-request!, page/block!, or page/authenticate! (a single id or a list of ids) and stop intercepting."
(for-each (fn (id) (cdp/off! pg id))
(if (list? interceptor-id) interceptor-id (list interceptor-id)))
(cdp/send pg "Fetch.disable")
nil)(page/stop-js-coverage pg)Stop coverage collection and return per-script {:url :used-bytes :total-bytes} (byte counts are an approximation from executed function ranges).
View source definition
(define (page/stop-js-coverage pg)
"Stop coverage collection and return per-script {:url :used-bytes :total-bytes} (byte counts are an approximation from executed function ranges)."
(let ((result (:result (cdp/send pg "Profiler.takePreciseCoverage"))))
(cdp/send pg "Profiler.stopPreciseCoverage")
(cdp/send pg "Profiler.disable")
(map script-coverage
(filter (fn (s) (not (= "" (or (:url s) "")))) result))))(page/stop-screencast! pg handle)Stop a screencast from page/start-screencast! and return the written frame paths, in order.
View source definition
(define (page/stop-screencast! pg handle)
"Stop a screencast from page/start-screencast! and return the written frame paths, in order."
(cdp/send pg "Page.stopScreencast")
(cdp/off! pg (:handler-id handle))
(sort (filter (fn (p) (string/contains? p "frame-"))
(map (fn (f) (format "~a/~a" (:dir handle) f))
(file/list (:dir handle))))))(page/text pg sel . opts-rest)Return the innerText of the element matching sel, auto-waiting for it to be attached. Options: :timeout ms.
View source definition
(define (page/text pg sel . opts-rest)
"Return the innerText of the element matching sel, auto-waiting for it to be attached. Options: :timeout ms."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(wait-state pg sel :attached (opt-timeout opts))
(page/eval pg (format "(el => el ? el.innerText : null)(~a)" (find-js sel)))))(page/texts pg sel)Return the innerText of every element matching sel, in document order. Empty list when nothing matches — does not wait.
View source definition
(define (page/texts pg sel)
"Return the innerText of every element matching sel, in document order. Empty list when nothing matches — does not wait."
(page/eval pg (format "(~a).map(el => el.innerText)" (find-all-js sel))))(page/title pg)Return the page's document title.
View source definition
(define (page/title pg)
"Return the page's document title."
(page/eval pg "document.title"))(page/track-console! pg)Start recording console output and uncaught page errors; read them with page/console.
View source definition
(define (page/track-console! pg)
"Start recording console output and uncaught page errors; read them with page/console."
(cdp/send pg "Runtime.enable")
nil)(page/track-network! pg)Start recording the page's network traffic (enables the Network domain). Events accumulate while commands run; read them with page/requests.
View source definition
(define (page/track-network! pg)
"Start recording the page's network traffic (enables the Network domain). Events accumulate while commands run; read them with page/requests."
(cdp/send pg "Network.enable")
nil)(page/type pg sel text . opts-rest)Focus the element matching sel and type text character by character with real key events — for pages reacting to each keystroke (autocomplete, masked inputs). Appends; use page/fill to replace. Options: :timeout ms.
View source definition
(define (page/type pg sel text . opts-rest)
"Focus the element matching sel and type text character by character with real key events — for pages reacting to each keystroke (autocomplete, masked inputs). Appends; use page/fill to replace. Options: :timeout ms."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(with-object pg (actionable-object pg sel (opt-timeout opts))
(fn (oid) (call-on pg oid "function(){ this.focus(); }")))
(for-each (fn (ch) (dispatch-key pg (char->string ch)))
(string->list text))
nil))(page/uncheck pg sel . opts-rest)Ensure the checkbox matching sel is unchecked (clicks only when needed). Options: :timeout ms.
View source definition
(define (page/uncheck pg sel . opts-rest)
"Ensure the checkbox matching sel is unchecked (clicks only when needed). Options: :timeout ms."
(set-checked pg sel #f (if (null? opts-rest) {} (first opts-rest))))(page/upload pg sel paths . opts-rest)Set the files of an <input type=file> matching sel. `paths` is a list of absolute file paths (or one path). Options: :timeout ms.
View source definition
(define (page/upload pg sel paths . opts-rest)
"Set the files of an <input type=file> matching sel. `paths` is a list of absolute file paths (or one path). Options: :timeout ms."
(let ((opts (if (null? opts-rest) {} (first opts-rest)))
(files (if (string? paths) (list paths) paths)))
(for-each (fn (p)
(when (not (file/exists? p))
(error (format "page/upload: file not found — ~a" p))))
files)
(with-object pg (actionable-object pg sel (opt-timeout opts))
(fn (oid)
(cdp/send pg "DOM.setFileInputFiles" {:files files :objectId oid})))
nil))(page/url pg)Return the page's current URL.
View source definition
(define (page/url pg)
"Return the page's current URL."
(page/eval pg "location.href"))(page/wait-for pg sel . opts-rest)Wait until the element matching sel reaches a state. Options: :state (:visible default, :attached, :hidden, :detached), :timeout ms (default 30000).
View source definition
(define (page/wait-for pg sel . opts-rest)
"Wait until the element matching sel reaches a state. Options: :state (:visible default, :attached, :hidden, :detached), :timeout ms (default 30000)."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(wait-state pg sel (get opts :state :visible) (get opts :timeout default-timeout))))(page/wait-for-download pg . opts-rest)Wait for the next download to finish and return {:path :filename :url}. Call page/downloads-to! first, then trigger the download (a click, a goto). Options: :timeout ms.
View source definition
(define (page/wait-for-download pg . opts-rest)
"Wait for the next download to finish and return {:path :filename :url}. Call page/downloads-to! first, then trigger the download (a click, a goto). Options: :timeout ms."
(let* ((opts (if (null? opts-rest) {} (first opts-rest)))
(timeout (opt-timeout opts))
(conn (:conn pg))
(begin-ev (cdp/wait-event conn "Browser.downloadWillBegin" {:timeout timeout}))
(guid (get-in begin-ev [:params :guid])))
(cdp/wait-event conn "Browser.downloadProgress"
{:timeout timeout
:pred (fn (ev)
(and (= guid (get-in ev [:params :guid]))
(= "completed" (get-in ev [:params :state]))))})
{:filename (get-in begin-ev [:params :suggestedFilename])
:url (get-in begin-ev [:params :url])
:path (format "~a/~a"
(mutable-cell/get download-dir)
(get-in begin-ev [:params :suggestedFilename]))}))(page/wait-for-function pg js . opts-rest)Poll a JS expression until it is truthy and return its value. Options: :timeout ms (default 30000), :interval ms (default 100).
View source definition
(define (page/wait-for-function pg js . opts-rest)
"Poll a JS expression until it is truthy and return its value. Options: :timeout ms (default 30000), :interval ms (default 100)."
(let* ((opts (if (null? opts-rest) {} (first opts-rest)))
(deadline (+ (time-ms) (opt-timeout opts)))
(interval (get opts :interval 100)))
(let loop ()
(let ((v (page/eval pg js)))
(cond (v v)
((> (time-ms) deadline)
(error (format "page/wait-for-function: timed out after ~ams — ~a"
(opt-timeout opts) js)))
(else (sleep interval) (loop)))))))(page/wait-for-response pg url-part . opts-rest)Wait for a response whose URL contains url-part and return it as a map (see page/requests). Requires page/track-network!. Options: :timeout ms.
View source definition
(define (page/wait-for-response pg url-part . opts-rest)
"Wait for a response whose URL contains url-part and return it as a map (see page/requests). Requires page/track-network!. Options: :timeout ms."
(let ((opts (if (null? opts-rest) {} (first opts-rest))))
(response-event->map
(cdp/wait-event pg "Network.responseReceived"
{:timeout (opt-timeout opts)
:pred (fn (ev)
(string/contains? (get-in ev [:params :response :url])
url-part))}))))(page/websocket-frames pg)Return WebSocket frames recorded since page/track-network! as {:url :direction (:sent or :received) :opcode :payload}, oldest first.
View source definition
(define (page/websocket-frames pg)
"Return WebSocket frames recorded since page/track-network! as {:url :direction (:sent or :received) :opcode :payload}, oldest first."
(let loop ((evs (cdp/events pg)) (urls {}) (acc (list)))
(if (null? evs)
acc
(let* ((ev (first evs))
(m (:method ev))
(rid (get-in ev [:params :requestId])))
(cond
((= m "Network.webSocketCreated")
(loop (rest evs) (assoc urls rid (get-in ev [:params :url])) acc))
((or (= m "Network.webSocketFrameSent")
(= m "Network.webSocketFrameReceived"))
(loop (rest evs) urls
(append acc
(list {:url (get urls rid)
:direction (if (= m "Network.webSocketFrameSent")
:sent :received)
:opcode (get-in ev [:params :response :opcode])
:payload (get-in ev [:params :response :payloadData])}))))
(else (loop (rest evs) urls acc)))))))About this reference
Generated with sema-reader 1.37.0 without executing package code. These are source declarations; dynamic exports, aliases, and runtime changes are not inferred.
Archive SHA-256 fc5bdfb1b7ff73623b66328dadfa93adc6323f63e52d69840540b20be663fc71