Repository navigation
Page Agent
The page agent is the content script that carries out page blocks inside a web page: it finds the element, waits until it is ready, dispatches the events and answers with plain data. Read this page when you add a page op, debug a "waiting for…" timeout, or need to know what an action really does to the DOM.
Source: agent.ts, agent.content.ts. Request/response types live in page.ts (see Page Protocol); the extension side is pageDriver.ts (see Browser Host).
Design rationale (why short calls, why synthetic events) is in ARCHITECTURE.md: Page blocks and the page agent and Harder pages.
| Step | Where | What happens |
|---|---|---|
| Build | agent.content.ts |
WXT content script with registration: 'runtime', matches: ['<all_urls>']. Bundled to /content-scripts/agent.js; never auto-injected. |
| Install | main() |
globalThis.__blockflowAgent ??= createAgent(). Re-injecting into the same document keeps the existing agent (and its lastRects). |
| Call | pageDriver.callOnce |
scripting.executeScript({ func, args: [call] }) in the default ISOLATED world, so it sees the content script's globalThis. The func returns __blockflowAgent.run(call) or {status: 'missing'}. |
| Missing | pageDriver.callAgent |
On missing, injects agent.js with files: and calls once more. A navigation gives a fresh document, so the next call re-injects. |
| Vanished | pageDriver.callOnce |
executeScript returned no result: the page went away mid-call. For actions (click, fill, set-field, select, check, press, drag, focus, blur, clear, dispatch) the driver returns {navigated: true} rather than repeat the action. |
| Frames | pageDriver.actInTab |
Target is the top frame unless the agent answered {status: 'frame'}; then the driver looks the frame up with webNavigation.getAllFrames (children of the current frame first; exact URL, else prefix match) and sends rest to that frameIds: [id], re-injecting there if needed. |
There is one agent per document (per frame). Same-origin iframes are entered by the top-frame agent
itself through contentDocument (see Locators: frames); only cross-origin frames
need their own agent.
export function createAgent(win: PageWindow = window as PageWindow, doc: Document = win.document): Agent;
export interface Agent { run(call: AgentCall): Promise<AgentResponse> }
export type PageWindow = Window & typeof globalThis;| Caller |
win / doc
|
Notes |
|---|---|---|
agent.content.ts |
page window / its document | The normal case. |
htmlParse.ts runOnHtml
|
offscreen (or Firefox background) window / a DOMParser document |
budgetMs: 0; no layout, so geometry checks are skipped. A frame answer becomes an error. |
tests/dom/agent.test.ts |
jsdom window / document | jsdom has no layout either. |
Constructors (MouseEvent, HTMLInputElement, DataTransfer…) are taken from win, never from the
global scope, so an agent can drive a document of another window.
hasLayout() is doc.documentElement.getBoundingClientRect().width > 0. When false (jsdom, parsed
HTML): visibility is style-only, isStable is always true, coveredBy always null, and event
coordinates are 0,0.
async run({ request, budgetMs }) {
const deadline = Date.now() + Math.max(0, budgetMs);
for (;;) {
try { return { status: 'done', result: attempt(request) }; }
catch (error) { /* map, or retry if Pending and before deadline */ }
await sleep(50); // RETRY_EVERY_MS, via win.setTimeout
}
}attempt is one synchronous try. It communicates by throwing:
| Thrown | Meaning | Answer |
|---|---|---|
| — (returns) | Success | {status: 'done', result} |
Pending(reason, code) |
Not possible yet | Retry every 50 ms; at the deadline {status: 'pending', reason, code, url} (the last reason). code defaults to timeout. |
Fatal(message, code?, matches?) |
Never going to work |
{status: 'error', message, code?, url, matches?} immediately. |
FrameBoundaryError |
Locator crosses into a cross-origin iframe (and no same-origin frame it matches has the element) |
{status: 'frame', src, rest} immediately; for locate / measure also offset (frame scrolled on screen), for box offset without scrolling. |
LocatorError |
Bad locator syntax/CSS/XPath/regex | Wrapped into Fatal(…, 'locator.invalid') by all(), so error. |
| anything else | Bug or page oddity |
{status: 'error', message, url} (no code: the engine records step.failed). run never rejects. |
The codes come from errors.ts; which check throws which is in Page Protocol: Error codes.
budgetMs comes from the driver: min(2000, timeLeft − 150). The driver keeps calling until the
block's timeout and then throws Timed out after Ns: <last reason>. With budgetMs: 0 the agent makes
exactly one attempt.
Results must survive executeScript structured cloning. Chrome sorts object keys on the way back, which
is why scraping ops return {columns, values} arrays (see
ARCHITECTURE.md: Data and scraping).
Field-level details of each request are in Page Protocol. This table is what the agent does with them.
| Op | Finds with | Readiness (ready(...)) |
Result |
|---|---|---|---|
click |
one (strict) |
visible, enabled (not for hover), stable, hit. All skipped with force. |
{clicked: describeElement, url} |
fill |
one |
visible, enabled, editable, stable | {value} |
set-field |
one |
visible, enabled, stable; editable only for text fields | depends on field kind, see below |
select |
one |
visible, enabled, stable | {selected: values[]} |
check |
one |
visible, enabled, stable | {changed, checked} |
press |
one if locator, else document.activeElement (or body) |
visible, enabled, stable (with locator); focuses it | {key} |
insert-text |
one if locator, else document.activeElement (or body) |
visible, enabled, editable, stable (with locator); focuses it unless focused | {text} |
read |
all (first match) |
none | {found: true, text, count} |
wait |
all |
none (the state is the wait) | {state, count?} |
detect-form |
all (first) |
none | {fields: FormFieldRow[], form: locator | null} |
info |
— | — | {url, title} |
extract |
all, per field resolveLocator(field.locator, item)[0]
|
none; Pending only if no items | {columns, values, count} |
table |
one |
none | {columns, values, count} |
page-info |
— | — | {url, title, description, canonical, lang, meta, jsonLd, links} |
storage |
— | — | {value} |
scroll |
one for to: 'element'
|
none | {height, y} |
upload |
one, then input / label.control / nested input[type=file] (with dropzone: the element itself) |
enabled only (hidden inputs allowed); drop zone: visible, stable |
{files: names[]} (+ dropped) |
focus / blur
|
one |
focus: visible; blur: none |
{focused} / {blurred}
|
clear |
one |
visible, enabled, editable | {value: ''} |
dispatch |
one |
none | {dispatched, defaultPrevented} |
drag |
one for source and to
|
source visible, stable, hit; target visible, stable | {dragged, to, mode, dropped} |
locate |
one |
visible, enabled, editable (fill, or set-field on a text field), stable, hit (purpose drop: visible, stable) |
{x, y, kind: 'text' | 'select' | 'check' | 'other'} (position instead of the center when given) |
snapshot |
body, or all(locator)[0] (Pending while none) |
none |
SnapshotResult: takeSnapshot() in snapshot.ts, plus url and title
|
box (M5.1) |
all (first match; no strict mode) |
none, answers at once, never scrolls |
{found: true, x, y, width, height, count, visible} (viewport, same-origin frame origins added) or {found: false, count: 0}
|
highlight (M5.1/M5.2) |
all (first match) |
none, answers at once |
{highlighted, count}; clear: true or no locator → {cleared: true}. Overlay div[data-blockflow-highlight] in the element's document (absolute, document coordinates, pointer-events: none, aria-hidden, label in a closed shadow root), replaces earlier ones, removed after ms
|
takeSnapshot(root, { maxLines }) builds the outline described in
Page Protocol: The snapshot op in two passes:
-
Walk the composed tree (shadow roots as rendered, slots by
assignedNodes, same-origin frames bycontentDocument) into items: role (getRole, plustextbox/buttonfor inputsaria.tsleaves without a role), name (only for targets and labelled elements: names from content cost a subtree walk), children (not for leaf roles: fields, selects, checkboxes, images), and merged text runs. Hidden subtrees are skipped (display:noneviagetComputedStyle,hidden,aria-hidden). The walk stops after3 × maxLinesitems. -
Render until
maxLines − 1lines, adding flags and, for targets,[ref=eN] locator=…fromfirstLocatorin bestLocator.ts (prefixedframe=… >>in frames). Locator lookups share a per-document cache, and the whole snapshot runs insidewithAriaMemo(aria.ts), which remembers names and hidden states: hundreds of locator checks ask about the same elements. After 4 s of locator work, the rest getgenerateSelector.
one(locator) is Playwright's strict mode: zero matches is Pending("waiting for X: no element matches"), two or more is Fatal listing up to three matches with describeElement and suggesting
>> nth=0. Reads, waits, extract and detect-form use all and are not strict.
describeElement(el) (from locator.ts) produces button#save.primary "Save changes": tag, id, first two classes, and up to 40 chars of accessible name or text. It appears in most
messages.
ready(element, { enabled?, editable?, hit? }) runs these checks in order and throws Pending with the
first failing reason:
| Check | Rule | Reason text |
|---|---|---|
| Visible | connected; no [hidden] ancestor; no display:none on it or an ancestor; not visibility: hidden/collapse on itself; non-empty box (layout only). Opacity is not checked. |
waiting for X to be visible |
| Enabled | not .disabled; not in fieldset[disabled] (unless inside its legend); no [aria-disabled="true"] ancestor |
waiting for X to be enabled |
| Editable | not readOnly; not aria-readonly="true"
|
waiting for X to be editable (it is read-only) |
| Scroll | if the box is outside the viewport, scrollIntoView({block: 'center', inline: 'center'})
|
— |
| Stable | same rounded x,y,w,h as at the previous look (kept in a WeakMap per agent) |
waiting for X to stop moving |
| Hit |
elementFromPoint(center) (descending into shadow roots) is the element, inside it, a <label> for it, or in a shadow tree hosted by it |
X is covered by Y |
Gotchas:
- Stability needs two looks, so the first attempt on a never-seen element is always Pending; an action takes at least one 50 ms retry when there is layout. A scroll-into-view also causes one "stop moving".
- Hit-testing uses the element's own document, so coordinates are those of its frame.
-
checkandselectdo not requirehit, so a native checkbox covered by a custom styled box still works (it is clicked synthetically).
All events are created with win's constructors and are isTrusted: false. Mouse and keyboard events
are composed: true, so they cross shadow boundaries.
| Action | Events (in order) | Default action done by the agent |
|---|---|---|
| hover | pointerover, pointerenter, mouseover, mouseenter, pointermove, mousemove | — |
| click | hover set, then pointerdown, mousedown, (focus unless mousedown cancelled), pointerup, mouseup, click | The browser runs click's default action for dispatched clicks (follow link, toggle checkbox, submit). |
| double | the press sequence twice (detail 1, 2), dblclick after the second click |
— |
| right | press sequence with button: 2, contextmenu instead of click (kept as before M2: no auxclick, which real Chrome also sends) |
— |
middle (button: 'middle') |
press sequence with button: 1, auxclick instead of click
|
— |
| click options |
modifiers set altKey/ctrlKey/metaKey/shiftKey on every event (hover too); position sets clientX/Y (padding box corner + x,y); clickCount: n repeats the press n times (detail 1…n), dblclick after the 2nd left press |
— |
| focus / blur |
focus() on the element or its closest focusable ancestor / blur() on the focused element when it is the element or inside it |
— |
| clear | as fill with ''
|
value emptied |
| dispatch | one event, see Page Protocol | the browser's default for dispatched events only |
fill (mode: 'fill') |
focus, native value setter, input (InputEvent insertText), change
|
value set |
fill (mode: 'type') |
clear (input deleteContentBackward), then per char keydown, keypress, value += char, input, keyup; then change
|
char added only if keydown and keypress were not cancelled |
| fill (contenteditable) | select contents, execCommand('insertText'), else textContent = + input
|
— |
| select | focus, native setter (or option.selected for multiple), input, change
|
— |
| check | a full click, then verifies checkedState changed (Fatal if not) |
— |
| press | keydown per held modifier (Control, Alt, Meta, Shift; each carrying the modifiers held so far), keydown, keypress (printable or Enter), keyup, keyup per modifier in reverse | printable char typed into inputs/textarea; Enter adds \n in textarea, form.requestSubmit() in inputs, .click() on a/button; Backspace deletes; Tab / Shift+Tab focus the next/previous tabbable; Ctrl+A (Meta+A on a Mac) selects the field or a contenteditable's content |
| insert-text |
execCommand('insertText') on the focused field when the browser does it (it fires beforeinput/input itself); else the selection is replaced through the native setter, caret after the text, one input (insertText) |
no key events at all |
| upload |
input.files = DataTransfer.files, input, change
|
— |
| upload, drop zone | dragenter, dragover (must be cancelled), drop, each a DragEvent carrying one DataTransfer with the files (types includes Files); dragleave instead of drop when dragover was not cancelled |
— |
drag() takes the source's point (center or fromPosition) and the target's (center or toPosition). After
the hover set, pointerdown and mousedown on the source:
-
HTML5 path, when the source is draggable (
draggable="true"on it or an ancestor, or a link/image that is notdraggable="false") and itsdragstartis not cancelled: one DataTransfer (new DataTransfer(), or a stand-in with the same methods where it cannot be constructed) travels through dragstart, pointercancel, drag, dragenter and dragover on the element under the target point, then drop when dragover was cancelled (withdropEffectset fromeffectAllowed) or dragleave when not, then dragend on the source. No pointerup/mouseup follow, as in browsers.{mode: 'html5', dropped}. -
Pointer path otherwise (sliders, pointer-event sortables, canvases): 5 pointermove/mousemove steps
with
buttons: 1, then pointerup/mouseup at the target point. Pointer events go to the source, as they would to an element that captured the pointer (the content script runs in an isolated world, so it cannot see or emulate the page'ssetPointerCapture); mouse events go to the element under each point. Code that listens on the document gets both.{mode: 'pointer'}.
With real input the driver drags with CDP instead: see Browser Host.
Native setter. setNativeValue calls the value setter from HTMLInputElement.prototype (or
TextArea/Select), bypassing the instance-level property React installs to track value. That makes React,
Vue and Angular see the following input event as a change.
Key names. parseKey('Control+Shift+a') splits on +; modifiers are ctrl/control, shift,
alt, meta/cmd/command, and ControlOrMeta (Meta when navigator.platform is a Mac, else Control),
case-insensitive. With Shift a lowercase letter becomes uppercase (Shift+a types A, as Playwright).
code is KeyA / Digit1 for single characters, ControlLeft… for modifier keys, else the key name itself.
Text fields. textKind: textarea; input of type '', text, email, password, search, tel, url,
number, date, time, datetime-local, month, week, color, range; or contenteditable. Anything else makes
fill Fatal ("cannot be typed into. Use Select Option, Check or Click instead").
set-field picks by element: <select> → select with the value split on |; checkbox / radio /
ARIA switch → check with true/yes/on/1/checked meaning checked; file input → Fatal; otherwise
fill.
With step.realInput, pageDriver.ts sends {op: 'locate'} first (same
waits as the action), takes {x, y} and drives chrome.debugger Input.* events instead
(cdp.ts). The agent's only role is waiting and reporting the center and field
kind (or the position point); set-field on non-text fields and all non-action ops fall back to the
synthetic path. See
Browser Host.
Coordinates are the tab's, also inside frames: for an element in a same-origin frame, locate brings the
frames around it on screen and adds each frame's content origin (getBoundingClientRect() + clientLeft/Top
- padding), walking
frameElementup to its own document. When the locator hands over to a cross-origin frame, theframeanswer to alocatecarriesoffset(that iframe's content origin in this frame's viewport, after scrolling it into view), and the driver adds the offsets of every hop to the inner agent's{x, y}. Page zoom and CSS transforms around a frame are not accounted for.
| Area | Behaviour |
|---|---|
| Finding | CSS needs >>> to step into open shadow roots; text/role/label/placeholder/alt/title/testid engines search shadow trees automatically (allElements). XPath does not. Closed roots are invisible. |
| Hit test |
coveredBy descends through shadowRoot.elementFromPoint and accepts hits inside a shadow tree hosted by the target. |
| Events |
composed: true, dispatched on the found element itself. |
| Tab order |
tabbables() uses doc.querySelectorAll, so shadow content is skipped. |
read takes the first match and is not strict:
kind |
No match | Value |
|---|---|---|
count, exists
|
answers (0 / false) |
String(count) / String(count > 0)
|
visible |
answers false
|
any match visible |
checked |
answers false
|
first match checkedState === true
|
enabled |
answers false
|
first match enabled and visible |
text |
Pending | raw textContent (not normalized: Watch Element compares like with like) |
value |
Pending |
.value if the element has one, else ''
|
attribute |
Pending | getAttribute(name) ?? '' |
has-class |
Pending | classList.contains(name) |
class |
Pending | the class attribute, whitespace collapsed |
css |
Pending (Fatal config.invalid without name) |
getComputedStyle(el).getPropertyValue(name), trimmed |
accessible-name / accessible-description
|
Pending |
accessibleName / accessibleDescription (aria.ts) |
focused |
answers false
|
the first match is its document's active element (descending into open shadow roots' activeElement) |
editable |
answers false
|
a field (input except hidden, textarea, select, contenteditable, or role textbox/searchbox/combobox/spinbutton/slider/checkbox/radio/switch/listbox), enabled, not readOnly, not aria-readonly
|
in-viewport |
answers false
|
an IntersectionObserver (the element's window's) is asked once: ratio > 0. A background tab may never answer, so after 500 ms the box decides (intersects the top window's viewport, frame offsets added; no layout → false). attempt returns a promise only for this read. |
wait text states use innerText (falling back to textContent) of each match, or of body, through
textMatcher (substring, "exact" or /regex/).
Scraping helpers: textOf collapses whitespace; attributeOf resolves href, src, action, poster,
data-src against doc.baseURI. table uses <thead>'s first row, else the first row with a <th>,
else the first row as headers (empty header → columnN).
What a block ends up seeing (after pageDriver.ts):
| Source | Example message |
|---|---|
| Fatal: strict | #list li matches 3 elements (li "One", li "Two", li "Three"). Make it more specific, or add ">> nth=0" for the first one. |
| Fatal: locator |
Invalid CSS selector: ##, Unknown role option [bogus]. Use name, exact, checked, level., nth needs a whole number: nth=x
|
| Fatal: wrong element |
select#x is not a <select>. Use Click to open custom dropdowns., … is not a checkbox, radio or switch, A radio button cannot be unchecked; check another one instead
|
| Pending at timeout |
Timed out after 30s: waiting for button "Save" to be enabled (code element.disabled) |
| Driver |
The tab was closed (tab.closed), The browser does not let extensions work on this page: … (permission.missing / page.restricted), Timed out after Ns: the page navigated (timeout) |
Every one of them is a CodedError (src/core/errors.ts) carrying code, the request's locator, the
page url and, for strict-mode errors, matches; the engine copies them onto the step record.
-
src/dom/*runs inside web pages: onlyimport typefrom the extension, plus puresrc/coremodules (locatorSyntax.ts). Nobrowser.*. -
isTrustedis false for everything; sites that check it need real input. - Firefox, background tab:
element.focus()moves focus without firingfocus/blur(the window has no focus).focus()andblur()inagent.tsnotice that the event did not fire and dispatchfocus+focusin/blur+focusoutthemselves; in Chrome the native events fire and nothing is added. - Firefox, drop zones: during an untrusted
drop, a content-script DataTransfer shows its file initemsbut an emptyfiles.exposeFilesdefinesfileson the page's view of the transfer (wrappedJSObject) from a second DataTransfer; no-op in Chrome. - Opacity-0 and off-screen-clipped elements count as visible.
-
selectonly drives native<select>; custom dropdowns are clicks. - New op checklist: add it to
AgentRequestinpage.ts, acaseinattempt, a jsdom test intests/dom/agent.test.ts, then the block. See Adding a Block.
- Page Protocol: request and response fields
-
Locators: what
one/allresolve -
Browser Host:
pageDriver.ts, real input, offscreen HTML parsing - Picker and Recorder: the other two content scripts
- Testing: jsdom tests and e2e
Generated from docs/wiki in the repo by npm run wiki:publish. Edit the repo files, not this wiki.
Using BlockFlow
- What is BlockFlow
- Installing
- Getting Started
- Concepts
- Using the Editor
- Workflows as Scripts
- Recipes
- Capabilities and Limitations
- Troubleshooting
- Roadmap
Reference
Internals: engine
Internals: browser
Outside access (M4)
Internals: page and editor
Project