The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
feat(ego-browser): improve complex page editing
Autecbde1f42ac92
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjsindex 58ae380..67b35be 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-keyboard.mjs@@ -35,6 +35,48 @@ export function pageKeyboardInterfaceCase() {"page.focus addresses one selector");+ await page.evaluate(() => {+ const wrapper = document.createElement("div");+ wrapper.id = "deep-focus-wrapper";+ wrapper.innerHTML =+ '<div><section><div><input id="deep-focus-input" /></div></section></div>';+ document.body.append(wrapper);++ const editor = document.createElement("div");+ editor.id = "focus-ancestor-editor";+ editor.contentEditable = "true";+ editor.innerHTML = '<span><em id="focus-descendant-text">editable</em></span>';+ document.body.append(editor);++ const slottedEditor = document.createElement("div");+ slottedEditor.id = "slotted-focus-host";+ slottedEditor.attachShadow({ mode: "open" }).innerHTML =+ '<button id="slotted-button"><slot></slot></button>';+ slottedEditor.innerHTML = '<span id="slotted-focus-text">slotted button</span>';+ document.body.append(slottedEditor);+ });+ await page.focus("#deep-focus-wrapper");+ assertEqual(+ await page.evaluate("document.activeElement?.id"),+ "deep-focus-input",+ "page.focus descends through any number of wrappers to one focusable target"+ );+ await page.focus("#focus-descendant-text");+ assertEqual(+ await page.evaluate("document.activeElement?.id"),+ "focus-ancestor-editor",+ "page.focus climbs through any number of wrappers to a focusable ancestor"+ );+ await page.focus("#slotted-focus-text");+ assertEqual(+ await page.evaluate(+ "document.querySelector('#slotted-focus-host').shadowRoot.activeElement?.id",+ ),+ "slotted-button",+ "page.focus follows the composed parent chain through a slot"+ );+ await page.focus("#text-area");+// U+0020 through U+007E covers every printable ASCII character.const printable = Array.from({ length: 95 },@@ -166,6 +208,27 @@ export function pageKeyboardInterfaceCase() {"paste uses native clipboard input and preserves tabs and newlines");+ await page.evaluate(() => {+ const editor = document.createElement("div");+ editor.id = "html-paste-editor";+ editor.contentEditable = "true";+ editor.style.cssText = "width:300px;min-height:80px;background:white";+ document.body.append(editor);+ editor.focus();+ });+ await page.keyboard.paste({+ text: "Name\\tStatus",+ html: "<table><tr><td>Name</td><td>Status</td></tr></table>",+ });+ const richPaste = await page.evaluate(() => ({+ table: Boolean(document.querySelector("#html-paste-editor table")),+ text: document.querySelector("#html-paste-editor").innerText,+ }));+ assertEqual(richPaste.table, true, "paste exposes HTML to rich editors");+ assertIncludes(richPaste.text, "Name", "HTML paste keeps its text visible");+ assertIncludes(richPaste.text, "Status", "HTML paste preserves every table cell");+ await page.focus("#text-area");+await page.evaluate("window.__pageKeyboardContractEvents = []");await page.keyboard.press("Numpad1");const numpadEvent = (await page.evaluate("window.__pageKeyboardContractEvents"))diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjsindex b43ec88..6a527c2 100644--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs@@ -329,6 +329,31 @@ export function pageBasicOperationsCase() {"fixture-upload.txt","page.setInputFiles follows a label to its file input");+ await first.evaluate(() => {+ const shadowHost = document.createElement("div");+ shadowHost.id = "shadow-file-wrapper";+ shadowHost.attachShadow({ mode: "open" }).innerHTML =+ '<section><input id="shadow-file-input" type="file" /></section>';+ document.body.append(shadowHost);++ const ambiguous = document.createElement("div");+ ambiguous.id = "ambiguous-file-wrapper";+ ambiguous.innerHTML = '<input type="file" /><input type="file" />';+ document.body.append(ambiguous);+ });+ await first.setInputFiles("#shadow-file-wrapper", uploadPath);+ assertEqual(+ await first.evaluate(+ "document.querySelector('#shadow-file-wrapper').shadowRoot.querySelector('#shadow-file-input').files[0].name",+ ),+ "fixture-upload.txt",+ "page.setInputFiles searches nested open shadow roots"+ );+ await assertRejects(+ () => first.setInputFiles("#ambiguous-file-wrapper", uploadPath),+ "multiple file inputs",+ "page.setInputFiles refuses to choose the first of multiple descendants"+ );await assertRejects(() => first.click("#dynamic-file-button"),@@ -410,6 +435,48 @@ export function pageActionsAndPopupCase() {);assertEqual((await currentTab()).targetId, source.targetId, "page.fill activates and keeps its page current");+ await source.evaluate(() => {+ const wrapper = document.createElement("div");+ wrapper.id = "fill-descendant-wrapper";+ wrapper.innerHTML = '<section><div><input id="fill-descendant-input" /></div></section>';+ document.body.append(wrapper);++ const editor = document.createElement("div");+ editor.id = "fill-ancestor-editor";+ editor.contentEditable = "true";+ editor.innerHTML = '<span><em id="fill-ancestor-text">old text</em></span>';+ document.body.append(editor);++ const ambiguous = document.createElement("div");+ ambiguous.id = "ambiguous-fill-wrapper";+ ambiguous.innerHTML = '<input id="ambiguous-fill-a" /><input id="ambiguous-fill-b" />';+ document.body.append(ambiguous);+ });+ await source.fill("#fill-descendant-wrapper", "nested input");+ assertEqual(+ await source.evaluate("document.querySelector('#fill-descendant-input').value"),+ "nested input",+ "page.fill descends through wrappers to one fillable target"+ );+ await source.fill("#fill-ancestor-text", "ancestor editor");+ assertEqual(+ await source.evaluate("document.querySelector('#fill-ancestor-editor').innerText"),+ "ancestor editor",+ "page.fill climbs to the nearest editing host"+ );+ await assertRejects(+ () => source.fill("#ambiguous-fill-wrapper", "must not choose"),+ "multiple fillable targets",+ "page.fill refuses to choose between multiple editable descendants"+ );+ assertEqual(+ await source.evaluate(+ "document.querySelector('#ambiguous-fill-a').value + document.querySelector('#ambiguous-fill-b').value",+ ),+ "",+ "an ambiguous page.fill does not modify either field"+ );+await source.evaluate(() => {const editor = document.createElement("div");editor.id = "pointer-activated-editor";@@ -440,6 +507,28 @@ export function pageActionsAndPopupCase() {"page.fill uses only one pointer fallback after the standard fill is rejected");+ await source.evaluate((popupUrl) => {+ const editor = document.createElement("div");+ editor.id = "linked-rich-editor";+ editor.contentEditable = "true";+ editor.style.cssText =+ "position:fixed;left:300px;top:160px;width:240px;height:40px;background:white;z-index:1000";+ editor.innerHTML =+ '<a href="' + popupUrl + '" target="_blank" style="display:block;width:100%;height:100%">linked text</a>';+ editor.addEventListener("beforeinput", (event) => event.preventDefault());+ document.body.append(editor);+ }, baseUrl + "/secondary?unsafe-fill-popup=1");+ await assertRejects(+ () => source.fill("#linked-rich-editor", "must not navigate"),+ "cannot safely activate",+ "page.fill refuses a pointer fallback that would click an editor link"+ );+ assertEqual(+ (await task.tabs()).some((item) => item.url.includes("unsafe-fill-popup")),+ false,+ "a rejected fill does not open the interactive descendant"+ );+await source.evaluate((popupUrl) => {const area = document.createElement("div");area.innerHTML = String.raw\`diff --git a/package/ego-browser/src/clipboard.test.mjs b/package/ego-browser/src/clipboard.test.mjsindex 2a36d51..abdc7e3 100644--- a/package/ego-browser/src/clipboard.test.mjs+++ b/package/ego-browser/src/clipboard.test.mjs@@ -3,6 +3,7 @@ import assert from "node:assert/strict";import {ClipboardRestoreError,+ withTemporaryClipboardContent,withTemporaryClipboardText,} from "../dist/src/clipboard.js";@@ -31,6 +32,27 @@ test("temporary clipboard text is restored after the action", async () => {assert.deepEqual(events, [["begin", "temporary"], "action", "finish"]);});+test("temporary clipboard content keeps text and HTML representations together", async () => {+ const content = {+ text: "A\tB",+ html: "<table><tr><td>A</td><td>B</td></tr></table>",+ };+ let prepared;++ await withTemporaryClipboardContent(content, async () => {}, {+ async beginTransaction(value) {+ prepared = value;+ return {+ async finish() {+ return "restored";+ },+ };+ },+ });++ assert.deepEqual(prepared, content);+});+test("temporary clipboard text is restored when the action throws", async () => {let finished = false;const primary = new Error("paste input failed");diff --git a/package/ego-browser/src/clipboard.ts b/package/ego-browser/src/clipboard.tsindex 284e7ef..9cea70f 100644--- a/package/ego-browser/src/clipboard.ts+++ b/package/ego-browser/src/clipboard.ts@@ -7,8 +7,15 @@ export type ClipboardTransaction = {finish(): Promise<ClipboardTransactionStatus>;};+export type ClipboardContent = {+ text: string;+ html?: string;+};++type ClipboardInput = string | ClipboardContent;+type ClipboardTransactionOptions = {- beginTransaction?: (text: string) => Promise<ClipboardTransaction>;+ beginTransaction?: (content: ClipboardInput) => Promise<ClipboardTransaction>;};type ClipboardHostMessage = {@@ -37,13 +44,11 @@ let transactionQueue: Promise<void> = Promise.resolve();* single user resource shared by every Page.*/export async function withTemporaryClipboardText<T>(- text: string,+ text: ClipboardInput,action: () => Promise<T>,options: ClipboardTransactionOptions = {},): Promise<T> {- if (typeof text !== "string") {- throw new TypeError("page.keyboard.paste text must be a string");- }+ const content = validateClipboardInput(text);if (typeof action !== "function") {throw new TypeError("clipboard action must be a function");}@@ -58,7 +63,7 @@ export async function withTemporaryClipboardText<T>(try {const beginTransaction =options.beginTransaction ?? beginDarwinClipboardTransaction;- const transaction = await beginTransaction(text);+ const transaction = await beginTransaction(content);let value!: T;let actionError: unknown;try {@@ -92,13 +97,22 @@ export async function withTemporaryClipboardText<T>(}}+/** Temporarily publish multiple representations of the same clipboard value. */+export async function withTemporaryClipboardContent<T>(+ content: ClipboardContent,+ action: () => Promise<T>,+ options: ClipboardTransactionOptions = {},+): Promise<T> {+ return withTemporaryClipboardText(content, action, options);+}+/*** Keep the original NSPasteboard items inside a short-lived JXA process. The* data never crosses stdout or enters the Node heap, and every readable format* is restored unless another process changes the clipboard first.*/async function beginDarwinClipboardTransaction(- text: string,+ input: ClipboardInput,): Promise<ClipboardTransaction> {if (process.platform !== "darwin") {throw new Error(@@ -125,7 +139,7 @@ async function beginDarwinClipboardTransaction(child.once("exit", (code, signal) => resolve({ code, signal }));});- child.stdin.end(text, "utf8");+ child.stdin.end(JSON.stringify(input), "utf8");const first = await nextHostMessage(messages, exit, () => stderr);if (first.state !== "ready") {throw new Error(first.message || "could not prepare the macOS clipboard");@@ -156,6 +170,31 @@ async function beginDarwinClipboardTransaction(};}+function validateClipboardInput(input: ClipboardInput): ClipboardInput {+ if (typeof input === "string") return input;+ if (!input || typeof input !== "object" || Array.isArray(input)) {+ throw new TypeError(+ "page.keyboard.paste requires a string or { text, html? }",+ );+ }+ const keys = Object.keys(input);+ const unknown = keys.find((key) => key !== "text" && key !== "html");+ if (unknown) {+ throw new TypeError(+ `page.keyboard.paste received unknown content field: ${unknown}`,+ );+ }+ if (typeof input.text !== "string") {+ throw new TypeError("page.keyboard.paste content.text must be a string");+ }+ if (input.html !== undefined && typeof input.html !== "string") {+ throw new TypeError("page.keyboard.paste content.html must be a string");+ }+ return input.html === undefined+ ? { text: input.text }+ : { text: input.text, html: input.html };+}+function clipboardMessages(stream: NodeJS.ReadableStream) {const queued: ClipboardHostMessage[] = [];const waiters: Array<{@@ -287,16 +326,24 @@ function restorePasteboard(snapshot) {}const input = $.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile;-const text = ObjC.unwrap(+const serialized = ObjC.unwrap($.NSString.alloc.initWithDataEncoding(input, $.NSUTF8StringEncoding));+const parsed = JSON.parse(serialized);+const content = typeof parsed === "string" ? { text: parsed } : parsed;const saved = snapshotPasteboard();try {pasteboard.clearContents;- if (!pasteboard.setStringForType($(text), $.NSPasteboardTypeString)) {+ if (!pasteboard.setStringForType($(content.text), $.NSPasteboardTypeString)) {throw new Error("NSPasteboard rejected the temporary text");}+ if (+ content.html !== undefined &&+ !pasteboard.setStringForType($(content.html), $.NSPasteboardTypeHTML)+ ) {+ throw new Error("NSPasteboard rejected the temporary HTML");+ }} catch (error) {try { restorePasteboard(saved); } catch (_) {}emit({ state: "error", message: String(error.message || error) });diff --git a/package/ego-browser/src/driver/action-target.ts b/package/ego-browser/src/driver/action-target.tsnew file mode 100644index 0000000..638552c--- /dev/null+++ b/package/ego-browser/src/driver/action-target.ts@@ -0,0 +1,96 @@+/**+ * Browser-side helpers shared by selector actions that need composed-tree+ * relationships. Keep action policy at each call site: pointer actions and+ * editing actions intentionally do not retarget in the same way.+ */+export const COMPOSED_PARENT_HELPER = `+ function composedParent(element) {+ if (element?.assignedSlot) return element.assignedSlot;+ if (element?.parentElement) return element.parentElement;+ const root = element?.getRootNode ? element.getRootNode() : null;+ return root && root.nodeType === 11 ? root.host : null;+ }+`;++export const COMPOSED_TREE_HELPERS = `+ ${COMPOSED_PARENT_HELPER}+ function composedChildren(element) {+ if (!element) return [];+ if (String(element.tagName || "").toUpperCase() === "SLOT") {+ const assigned = element.assignedElements?.({ flatten: true }) || [];+ if (assigned.length > 0) return assigned;+ }+ const container = element.shadowRoot || element;+ return Array.from(container.children || []);+ }+ function nearestComposedAncestor(element, predicate) {+ let current = composedParent(element);+ while (current) {+ if (predicate(current)) return current;+ current = composedParent(current);+ }+ return null;+ }+ function composedDescendantMatches(root, predicate, stopAtMatch = false) {+ const matches = [];+ const visit = (parent) => {+ for (const child of composedChildren(parent)) {+ const matched = predicate(child);+ if (matched) matches.push(child);+ if (!(matched && stopAtMatch)) visit(child);+ }+ };+ visit(root);+ return matches;+ }+`;++/** Editing semantics layered on top of the shared composed-tree traversal. */+export const EDIT_ACTION_TARGET_HELPERS = `+ ${COMPOSED_TREE_HELPERS}+ function isExplicitContentEditable(element) {+ return Boolean(+ element?.hasAttribute?.("contenteditable") &&+ element.getAttribute("contenteditable") !== "false"+ );+ }+ function isFillableInput(element) {+ const tag = String(element?.tagName || "").toUpperCase();+ if (tag === "TEXTAREA") return true;+ if (tag !== "INPUT") return false;+ return new Set([+ "", "color", "date", "datetime-local", "email", "month", "number",+ "password", "range", "search", "tel", "text", "time", "url", "week"+ ]).has(String(element.type || "").toLowerCase());+ }+ function isFillableActionTarget(element) {+ return isExplicitContentEditable(element) || isFillableInput(element);+ }+ function isEditableFocusTarget(element) {+ const tag = String(element?.tagName || "").toUpperCase();+ if (isFillableActionTarget(element)) return !element.disabled;+ if (tag === "SELECT") return !element.disabled;+ return new Set(["textbox", "searchbox", "combobox", "spinbutton"]).has(+ String(element?.getAttribute?.("role") || "").toLowerCase()+ );+ }+ function isStrongFocusTarget(element) {+ if (!element?.isConnected || element.disabled || element.closest?.("[inert]")) {+ return false;+ }+ if (isEditableFocusTarget(element)) return true;+ const tag = String(element.tagName || "").toUpperCase();+ if (["BUTTON", "SELECT", "TEXTAREA", "SUMMARY", "IFRAME"].includes(tag)) {+ return true;+ }+ if (tag === "INPUT") return String(element.type || "").toLowerCase() !== "hidden";+ if ((tag === "A" || tag === "AREA") && element.hasAttribute("href")) return true;+ if ((tag === "AUDIO" || tag === "VIDEO") && element.hasAttribute("controls")) {+ return true;+ }+ return new Set([+ "button", "checkbox", "link", "menuitem", "menuitemcheckbox",+ "menuitemradio", "option", "radio", "slider", "switch", "tab", "treeitem"+ ]).has(String(element.getAttribute?.("role") || "").toLowerCase());+ }+`;diff --git a/package/ego-browser/src/driver/page-actions.ts b/package/ego-browser/src/driver/page-actions.tsindex 9e39774..b39dd71 100644--- a/package/ego-browser/src/driver/page-actions.ts+++ b/package/ego-browser/src/driver/page-actions.ts@@ -4,6 +4,10 @@ import {resolveElementObjectId,} from "../element-resolver.js";import { RefMap } from "../ref-map.js";+import {+ COMPOSED_PARENT_HELPER,+ EDIT_ACTION_TARGET_HELPERS,+} from "./action-target.js";type PageActionServices = {cdp(@@ -204,7 +208,13 @@ export async function fillInPage(iframeSessions,{ strict: true },);+ let actionObjectId: string | undefined;try {+ actionObjectId = await resolveFillActionTarget(+ services,+ resolved.sessionId,+ resolved.objectId,+ );const preparationSource = `function fillPreparation(value, clearFirst) {if (!this.isConnected) return { error: "element is not connected" };const visibleCursorPoint = () => {@@ -272,7 +282,7 @@ export async function fillInPage("Runtime.callFunctionOn",{functionDeclaration: preparationSource,- objectId: resolved.objectId,+ objectId: actionObjectId,arguments: [{ value }, { value: clearFirst }],returnByValue: true,awaitPromise: false,@@ -305,7 +315,7 @@ export async function fillInPage(await verifyFilledValue(services,resolved.sessionId,- resolved.objectId,+ actionObjectId,value,clearFirst,)@@ -320,7 +330,7 @@ export async function fillInPage(await clickResolvedElement(services,resolved.sessionId,- resolved.objectId,+ actionObjectId,resolved.frameId,);result = await prepare();@@ -335,7 +345,7 @@ export async function fillInPage(await verifyFilledValue(services,resolved.sessionId,- resolved.objectId,+ actionObjectId,value,clearFirst,)@@ -349,14 +359,57 @@ export async function fillInPage(`page.fill did not accept the text. Click the ${target} and use page.keyboard, then verify the result.`,);} finally {- await services- .cdp(- "Runtime.releaseObject",- { objectId: resolved.objectId },- resolved.sessionId,- )- .catch(() => {});+ if (actionObjectId && actionObjectId !== resolved.objectId) {+ await releaseObject(services, resolved.sessionId, actionObjectId);+ }+ await releaseObject(services, resolved.sessionId, resolved.objectId);+ }+}++async function resolveFillActionTarget(+ services: PageActionServices,+ sessionId: string,+ objectId: string,+): Promise<string> {+ const source = `function resolveFillTargetForAction() {+ ${EDIT_ACTION_TARGET_HELPERS}+ const tag = String(this.tagName || "").toUpperCase();+ if (tag === "INPUT" || tag === "TEXTAREA" || isExplicitContentEditable(this)) {+ return this;+ }+ const editingHost = nearestComposedAncestor(this, isExplicitContentEditable);+ if (editingHost) return editingHost;+ const candidates = composedDescendantMatches(+ this,+ isFillableActionTarget,+ true,+ );+ if (candidates.length > 1) {+ throw new TypeError("page.fill selected an element with multiple fillable targets");+ }+ return candidates[0] || this;+ }`;+ const response = await services.cdp(+ "Runtime.callFunctionOn",+ {+ functionDeclaration: source,+ objectId,+ returnByValue: false,+ awaitPromise: false,+ },+ sessionId,+ );+ if (response?.exceptionDetails) {+ throw new ElementResolutionError(+ exceptionDescription(response),+ "permanent",+ );}+ const targetObjectId = response?.result?.objectId;+ if (!targetObjectId) {+ throw new Error("page.fill could not resolve an editable action target");+ }+ return targetObjectId;}/** Focus one strictly resolved element in an explicit Page session. */@@ -378,12 +431,65 @@ export async function focusInPage();const source = `function focusElementForAction() {if (!this.isConnected) return { error: "element is not connected" };- if (typeof this.focus !== "function") return { error: "element is not focusable" };- this.focus();- const active = this.ownerDocument.activeElement;- return active === this || this.contains(active)- ? { focused: true }- : { error: "element could not be focused" };+ ${EDIT_ACTION_TARGET_HELPERS}+ const deepActiveElement = () => {+ let active = this.ownerDocument.activeElement;+ while (active?.shadowRoot?.activeElement) {+ active = active.shadowRoot.activeElement;+ }+ return active;+ };+ const containsComposed = (container, element) => {+ let current = element;+ while (current) {+ if (current === container) return true;+ current = composedParent(current);+ }+ return false;+ };+ const details = () => ({+ tagName: this.tagName,+ contentEditable: Boolean(this.isContentEditable),+ tabIndex: this.tabIndex,+ activeTagName: deepActiveElement()?.tagName || null,+ });+ const tryFocus = (candidate, retargeted) => {+ if (typeof candidate.focus !== "function") return null;+ candidate.focus();+ const active = deepActiveElement();+ return active === candidate || containsComposed(candidate, active)+ ? { focused: true, retargeted }+ : null;+ };++ const direct = tryFocus(this, null);+ if (direct) return direct;++ let ancestor = composedParent(this);+ while (ancestor) {+ if (isStrongFocusTarget(ancestor)) {+ const focused = tryFocus(ancestor, "ancestor");+ if (focused) return focused;+ }+ ancestor = composedParent(ancestor);+ }++ const editableCandidates = composedDescendantMatches(+ this,+ isEditableFocusTarget,+ true,+ );+ if (editableCandidates.length === 1) {+ const focused = tryFocus(editableCandidates[0], "descendant");+ if (focused) return focused;+ }+ if (editableCandidates.length > 1) {+ return {+ error: "element contains multiple editable targets",+ details: { ...details(), candidateCount: editableCandidates.length },+ };+ }+ return { error: "element is not focusable", details: details() };}`;try {const response = await services.cdp(@@ -398,9 +504,16 @@ export async function focusInPage();const result = runtimeValue(response, source);if (typeof result?.error === "string") {+ const details = result.details;+ const candidateCount = details?.candidateCount+ ? `, candidates=${String(details.candidateCount)}`+ : "";+ const description = details+ ? ` (${String(details.tagName || "element").toLowerCase()}, contenteditable=${Boolean(details.contentEditable)}, tabIndex=${String(details.tabIndex)}, active=${String(details.activeTagName || "none").toLowerCase()}${candidateCount})`+ : "";throw new ElementResolutionError(- `page.focus failed: ${result.error}`,- "transient",+ `page.focus failed: ${result.error}${description}`,+ result.error === "element is not connected" ? "transient" : "permanent",);}} finally {@@ -514,6 +627,18 @@ async function clickResolvedElement(false,true,);+ await assertElementReceivesPointerEvents(+ services,+ sessionId,+ objectId,+ point.local,+ );+ await assertSafeFillActivationTarget(+ services,+ sessionId,+ objectId,+ point.local,+ );await dispatchMouseEvent(services, sessionId, {type: "mouseMoved",x: point.x,@@ -522,12 +647,6 @@ async function clickResolvedElement(buttons: 0,modifiers: 0,});- await assertElementReceivesPointerEvents(- services,- sessionId,- objectId,- point.local,- );await dispatchMouseEvent(services, sessionId, {type: "mousePressed",x: point.x,@@ -548,6 +667,45 @@ async function clickResolvedElement(});}+async function assertSafeFillActivationTarget(+ services: PageActionServices,+ sessionId: string,+ objectId: string,+ point: { x: number; y: number },+): Promise<void> {+ const expression = `function safeFillActivationTarget(point) {+ ${HIT_TARGET_HELPERS}+ if (!this.isConnected) return { error: "the editor is not connected" };+ const hit = hitElementAtPoint(this, point);+ let current = hit;+ while (current && current !== this) {+ if (isExplicitInteractiveElement(current)) {+ return { error: describeHitTarget(current) };+ }+ current = composedParent(current);+ }+ return { safe: true };+ }`;+ const response = await services.cdp(+ "Runtime.callFunctionOn",+ {+ functionDeclaration: expression,+ objectId,+ arguments: [{ value: point }],+ returnByValue: true,+ awaitPromise: false,+ },+ sessionId,+ );+ const result = runtimeValue(response, expression);+ if (typeof result?.error === "string") {+ throw new ElementResolutionError(+ `page.fill cannot safely activate the editor because ${result.error} would receive the click`,+ "permanent",+ );+ }+}+/** Move the native mouse over one element in an explicit Page session. */export async function hoverInPage(services: PageActionServices,@@ -994,17 +1152,20 @@ function fillPreparationError(message: string) {: new Error(`page.fill failed: ${message}`);}+function exceptionDescription(response: any): string {+ return (+ response?.exceptionDetails?.exception?.description ||+ response?.exceptionDetails?.text ||+ "page action evaluation failed"+ );+}+// This is a compact adaptation of Playwright's composed-tree hit-target check.// It handles ordinary descendants, slots, and nested shadow roots without// exposing an injected helper or trusting only document.elementFromPoint().const HIT_TARGET_HELPERS = `- function composedParent(element) {- if (element.assignedSlot) return element.assignedSlot;- if (element.parentElement) return element.parentElement;- const root = element.getRootNode ? element.getRootNode() : null;- return root && root.nodeType === 11 ? root.host : null;- }- function isInteractiveElement(element) {+ ${COMPOSED_PARENT_HELPER}+ function isExplicitInteractiveElement(element) {if (element?.matches?.(":disabled") ||element?.getAttribute?.("aria-disabled") === "true"@@ -1016,7 +1177,10 @@ const HIT_TARGET_HELPERS = `return true;}if (tag === "A" && element.hasAttribute?.("href")) return true;- if (element?.isContentEditable) return true;+ if (+ element?.hasAttribute?.("contenteditable") &&+ element.getAttribute("contenteditable") !== "false"+ ) return true;return new Set(["button","checkbox",@@ -1034,7 +1198,10 @@ const HIT_TARGET_HELPERS = `"treeitem"]).has(String(element?.getAttribute?.("role") || "").toLowerCase());}- function interceptingElementAtPoint(target, point) {+ function isInteractiveElement(element) {+ return isExplicitInteractiveElement(element) || Boolean(element?.isContentEditable);+ }+ function hitElementAtPoint(target, point) {const roots = [];let parent = target;while (parent) {@@ -1053,6 +1220,10 @@ const HIT_TARGET_HELPERS = `hitElement = innerElement;if (index > 0 && innerElement !== roots[index - 1].host) break;}+ return hitElement;+ }+ function interceptingElementAtPoint(target, point) {+ const hitElement = hitElementAtPoint(target, point);let current = hitElement;while (current && current !== target) current = composedParent(current);if (current === target) return null;@@ -1071,7 +1242,10 @@ const HIT_TARGET_HELPERS = `const id = element.id? ' id="' + String(element.id).slice(0, 80).replaceAll('"', '"') + '"': "";- return "<" + tag + id + ">";+ const href = tag === "a" && element.hasAttribute?.("href")+ ? ' href="' + String(element.getAttribute("href")).slice(0, 120).replaceAll('"', '"') + '"'+ : "";+ return "<" + tag + id + href + ">";}`;diff --git a/package/ego-browser/src/driver/page-input.ts b/package/ego-browser/src/driver/page-input.tsindex 8bb4301..314a877 100644--- a/package/ego-browser/src/driver/page-input.ts+++ b/package/ego-browser/src/driver/page-input.ts@@ -2,19 +2,32 @@ import { isAbsolute } from "node:path";import { resolveElementObjectId } from "../element-resolver.js";import { type RefMap } from "../ref-map.js";+import { COMPOSED_TREE_HELPERS } from "./action-target.js";import { type KeyboardServices } from "./keyboard.js";type PageInputServices = KeyboardServices;const RESOLVE_FILE_INPUT_SOURCE = `function resolveFileInputForUpload() {+ ${COMPOSED_TREE_HELPERS}const isFileInput = (element) =>- element instanceof HTMLInputElement && element.type === "file";+ String(element?.tagName || "").toUpperCase() === "INPUT" &&+ String(element.type || "").toLowerCase() === "file";if (isFileInput(this)) return this;- if (this instanceof HTMLLabelElement && isFileInput(this.control)) {+ const isFileLabel = (element) =>+ String(element?.tagName || "").toUpperCase() === "LABEL" &&+ isFileInput(element.control);+ if (isFileLabel(this)) {return this.control;}- const descendant = this.querySelector?.('input[type="file"]');- if (isFileInput(descendant)) return descendant;+ const label = nearestComposedAncestor(this, isFileLabel);+ if (label) return label.control;+ const descendants = composedDescendantMatches(this, isFileInput, true);+ if (descendants.length === 1) return descendants[0];+ if (descendants.length > 1) {+ throw new TypeError(+ "page.setInputFiles selected a container with multiple file inputs",+ );+ }throw new TypeError("page.setInputFiles requires a file input, its label, or a container with a file input",);diff --git a/package/ego-browser/src/driver/page-keyboard.ts b/package/ego-browser/src/driver/page-keyboard.tsindex dd7e88e..503463a 100644--- a/package/ego-browser/src/driver/page-keyboard.ts+++ b/package/ego-browser/src/driver/page-keyboard.ts@@ -7,12 +7,19 @@ export type PageKeyboardServices = {): Promise<any>;sleep(ms: number): Promise<void>;withTemporaryClipboardText<T>(- text: string,+ content: PageClipboardContent,action: () => Promise<T>,): Promise<T>;platform?: string;};+export type PageClipboardContent =+ | string+ | {+ text: string;+ html?: string;+ };+export type PageKeyboardPressOptions = {delay?: number;};@@ -137,10 +144,10 @@ export class PageKeyboardController {if (releaseError) throw releaseError;}- async paste(text: string): Promise<unknown> {- assertText(text, "page.keyboard.paste");+ async paste(content: PageClipboardContent): Promise<unknown> {+ assertClipboardContent(content);return this.#runObserved((sessionId) =>- this.#services.withTemporaryClipboardText(text, () =>+ this.#services.withTemporaryClipboardText(content, () =>this.pressInSession(sessionId, "ControlOrMeta+V"),),);@@ -228,6 +235,32 @@ export class PageKeyboardController {}}+function assertClipboardContent(+ content: unknown,+): asserts content is PageClipboardContent {+ if (typeof content === "string") return;+ if (!content || typeof content !== "object" || Array.isArray(content)) {+ throw new TypeError(+ "page.keyboard.paste requires a string or { text, html? }",+ );+ }+ const value = content as Record<string, unknown>;+ const unknown = Object.keys(value).find(+ (key) => key !== "text" && key !== "html",+ );+ if (unknown) {+ throw new TypeError(+ `page.keyboard.paste received unknown content field: ${unknown}`,+ );+ }+ if (typeof value.text !== "string") {+ throw new TypeError("page.keyboard.paste content.text must be a string");+ }+ if (value.html !== undefined && typeof value.html !== "string") {+ throw new TypeError("page.keyboard.paste content.html must be a string");+ }+}+/** Split a chord without losing a literal `+` key, matching Playwright. */export function splitChord(chord: string): string[] {if (typeof chord !== "string" || chord.length === 0) {diff --git a/package/ego-browser/src/index.ts b/package/ego-browser/src/index.tsindex c158ea5..c93bd98 100644--- a/package/ego-browser/src/index.ts+++ b/package/ego-browser/src/index.ts@@ -18,6 +18,7 @@ import {import { runMain } from "./run.js";import { installStaleEgoBrowserGuard } from "./skill-migration.js";import { emitUpdateNotice } from "./update-notice.js";+import { installPageContextGuard } from "./page-context-guard.js";type HelperFunction = (...args: unknown[]) => unknown;type EgoRuntime = Record<string, unknown> & {@@ -56,6 +57,7 @@ export function installEgoSdk(if (!target || typeof target !== "object") {return target;}+ if (target === globalThis) installPageContextGuard(target);const context = options.context || helpers.helperContext();const readySignal = Promise.resolve(options.ready);let readyError = null;diff --git a/package/ego-browser/src/page-context-guard.ts b/package/ego-browser/src/page-context-guard.tsnew file mode 100644index 0000000..c0081d0--- /dev/null+++ b/package/ego-browser/src/page-context-guard.ts@@ -0,0 +1,37 @@+const PAGE_CONTEXT_HINT =+ "Page JavaScript must run inside page.evaluate(); document is not available in the Node.js script.";++/** Add one actionable hint to the common Node-versus-Page context mistake. */+export function addPageContextHint(error: unknown): unknown {+ if (+ !(error instanceof ReferenceError) ||+ !/^document is not defined\.?$/i.test(error.message.trim())+ ) {+ return error;+ }+ if (error.message.includes("page.evaluate()")) return error;++ const originalMessage = error.message;+ error.message = `${originalMessage}. ${PAGE_CONTEXT_HINT}`;+ if (typeof error.stack === "string") {+ const lines = error.stack.split("\n");+ lines[0] = `${error.name}: ${error.message}`;+ error.stack = lines.join("\n");+ }+ return error;+}++/**+ * Install an SDK-only guard so the embedding host can print the same hint even+ * though it, rather than ego-browser's CLI wrapper, executes the heredoc.+ */+export function installPageContextGuard(target: Record<string, unknown>): void {+ if (Object.getOwnPropertyDescriptor(target, "document")) return;+ Object.defineProperty(target, "document", {+ configurable: true,+ enumerable: false,+ get() {+ throw new ReferenceError(`document is not defined. ${PAGE_CONTEXT_HINT}`);+ },+ });+}diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjsindex b2a56b1..b29dbe4 100644--- a/package/ego-browser/src/page-model.test.mjs+++ b/package/ego-browser/src/page-model.test.mjs@@ -44,6 +44,8 @@ function createFixture(rootDir) {let fillElementKind = "input";let fillText = "";let ignoredFillInsertionsRemaining = 0;+ let focusResult = { focused: true };+ let unsafeFillActivationTarget = null;let navigateOnNextClickUrl = null;let elementPresent = true;let elementVisible = true;@@ -219,7 +221,17 @@ function createFixture(rootDir) {if (method === "Runtime.callFunctionOn") {if (params.functionDeclaration.includes("focusElementForAction")) {return {- result: { type: "object", value: { focused: true } },+ result: { type: "object", value: focusResult },+ };+ }+ if (params.functionDeclaration.includes("safeFillActivationTarget")) {+ return {+ result: {+ type: "object",+ value: unsafeFillActivationTarget+ ? { error: unsafeFillActivationTarget }+ : { safe: true },+ },};}if (params.functionDeclaration.includes("resolveFileInputForUpload")) {@@ -231,6 +243,15 @@ function createFixture(rootDir) {},};}+ if (params.functionDeclaration.includes("resolveFillTargetForAction")) {+ const targetId = targetForSession(sessionId);+ return {+ result: {+ type: "object",+ objectId: `element:${targetId}`,+ },+ };+ }if (params.functionDeclaration.includes("fillPreparation")) {return {result: {@@ -565,6 +586,12 @@ function createFixture(rootDir) {fillText = initialText;ignoredFillInsertionsRemaining = ignoreInsertions;},+ configureFocusResult(result) {+ focusResult = result;+ },+ configureUnsafeFillActivation(target) {+ unsafeFillActivationTarget = target;+ },fillText: () => fillText,setElementState({ present = true, visible = true }) {elementPresent = present;@@ -1551,6 +1578,39 @@ test("Page fill retries an unchanged contenteditable once with a real click", as});});+test("Page fill refuses a pointer fallback that would activate an interactive descendant", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await task.openPage("https://example.test/editor");+ fixture.configureFill({+ kind: "contenteditable",+ initialText: "linked text",+ ignoreInsertions: 1,+ });+ fixture.configureUnsafeFillActivation(+ '<a href="https://example.test/link">',+ );+ fixture.calls.length = 0;++ await assert.rejects(+ () => page.fill("[contenteditable]", "replacement"),+ (error) => {+ assert.equal(error.kind, "permanent");+ assert.match(error.message, /cannot safely activate.*<a href=/i);+ return true;+ },+ );+ assert.equal(+ fixture.calls.some(+ ([kind, method]) =>+ kind === "cdp" && method === "Input.dispatchMouseEvent",+ ),+ false,+ "a fill fallback must not click an interactive descendant",+ );+ });+});+test("Page fill rejects when a contenteditable still ignores the pointer fallback", async () => {await withFixture(async (fixture) => {const task = taskForRound(fixture, "round-a");@@ -1929,6 +1989,56 @@ test("Page focus and selector-scoped press resolve and focus one element", async});});+test("Page focus accepts a uniquely retargeted descendant", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await task.openPage("https://example.test/editor");+ fixture.configureFocusResult({ focused: true, retargeted: "descendant" });++ assert.deepEqual(await page.focus("#editor-wrapper"), {});+ });+});++test("Page focus reports ambiguous candidates once as a permanent failure", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await task.openPage("https://example.test/editor");+ fixture.configureFocusResult({+ error: "element contains multiple editable targets",+ details: {+ tagName: "TD",+ contentEditable: false,+ tabIndex: -1,+ activeTagName: "BODY",+ candidateCount: 2,+ },+ });+ fixture.calls.length = 0;++ await assert.rejects(+ () => page.focus("td"),+ (error) => {+ assert.equal(error.kind, "permanent");+ assert.match(+ error.message,+ /multiple editable targets.*td.*contenteditable=false.*tabIndex=-1.*active=body.*candidates=2/i,+ );+ return true;+ },+ );+ assert.equal(+ fixture.calls.filter(+ ([kind, method, params]) =>+ kind === "cdp" &&+ method === "Runtime.callFunctionOn" &&+ params.functionDeclaration.includes("focusElementForAction"),+ ).length,+ 1,+ "a permanent focus failure must not consume the action timeout",+ );+ });+});+test("Page keyboard paste restores the clipboard after the native shortcut", async () => {await withFixture(async (fixture) => {const task = taskForRound(fixture, "round-a", { platform: "darwin" });@@ -1959,6 +2069,25 @@ test("Page keyboard paste restores the clipboard after the native shortcut", asy});});+test("Page keyboard paste forwards plain-text and HTML clipboard representations", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a", { platform: "darwin" });+ const page = await task.openPage("https://example.test/table");+ const content = {+ text: "A\tB",+ html: "<table><tr><td>A</td><td>B</td></tr></table>",+ };++ assert.deepEqual(await page.keyboard.paste(content), {});+ assert.deepEqual(+ fixture.calls.find(+ (call) => call[0] === "clipboard" && call[1] === "write",+ ),+ ["clipboard", "write", content],+ );+ });+});+test("Page keyboard paste still restores the clipboard when input fails", async () => {await withFixture(async (fixture) => {let restored = false;diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.tsindex 04e9553..32ae081 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -50,6 +50,7 @@ import {} from "./driver/page-input.js";import {PageKeyboardController,+ type PageClipboardContent,type PageKeyboardPressOptions,type PageKeyboardTypeOptions,} from "./driver/page-keyboard.js";@@ -252,7 +253,7 @@ type PageModelServices = {): Promise<any>;showAgentMousePosition(x: number, y: number): Promise<void>;withTemporaryClipboardText<T>(- text: string,+ content: PageClipboardContent,action: () => Promise<T>,): Promise<T>;snapshot(options?: SnapshotOptions): Promise<any>;@@ -472,8 +473,8 @@ class PageKeyboard {await this.#controller.pressInSession(sessionId, chord, options);}- async paste(text: string): Promise<PageActionReceipt> {- return (await this.#controller.paste(text)) as PageActionReceipt;+ async paste(content: PageClipboardContent): Promise<PageActionReceipt> {+ return (await this.#controller.paste(content)) as PageActionReceipt;}async insertText(text: string): Promise<void> {diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.tsindex 18e0424..a80af46 100644--- a/package/ego-browser/src/public-api-schema.ts+++ b/package/ego-browser/src/public-api-schema.ts@@ -387,7 +387,8 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [{name: "Page.fill",signature: "await page.fill(selector, value, { clearFirst?, timeout? })",- summary: "Focus and fill an input-like element, then verify its value.",+ summary:+ "Fill the selected field, its editing host, or its unique fillable descendant, then verify the value.",options: {clearFirst: option("boolean", "Clear the current value before filling."),timeout: actionTimeout,@@ -396,7 +397,8 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [{name: "Page.focus",signature: "await page.focus(selector, { timeout? })",- summary: "Resolve one element and focus it.",+ summary:+ "Focus the element, its nearest interactive ancestor, or its unique editable descendant.",options: { timeout: actionTimeout },},{@@ -408,7 +410,8 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [{name: "Page.setInputFiles",signature: "await page.setInputFiles(selector, pathOrPaths)",- summary: "Set files on a file input without opening the system chooser.",+ summary:+ "Set files on a file input resolved from the input, its label, or a unique descendant.",},{name: "Page.waitForFileChooser",@@ -518,9 +521,9 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [},{name: "Page.keyboard.paste",- signature: "await page.keyboard.paste(text)",+ signature: "await page.keyboard.paste(textOrContent)",summary:- "Send native paste and restore the clipboard; the focused page interprets the text.",+ "Send native paste with a string or { text, html? }, then restore the clipboard.",},] as const;diff --git a/package/ego-browser/src/run-output-sink.test.mjs b/package/ego-browser/src/run-output-sink.test.mjsindex b685900..4d5d204 100644--- a/package/ego-browser/src/run-output-sink.test.mjs+++ b/package/ego-browser/src/run-output-sink.test.mjs@@ -1,5 +1,6 @@import test from "node:test";import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";import { runMain } from "../dist/src/run.js";@@ -265,3 +266,22 @@ test("an ordinary uncaught error still flushes the output logged before it", asyassert.equal(result.error.message, "boom");assert.equal(result.stdout, "partial result\n");});++test("a top-level document ReferenceError explains the Page execution boundary", async () => {+ const result = await runScript(`console.log(document.body);`);++ assert.ok(result.error, "expected runMain to reject");+ assert.match(result.error.message, /document is not defined/i);+ assert.match(result.error.message, /page\.evaluate\(\)/i);+});++test("the direct CLI prints an ordinary uncaught error once", () => {+ const entry = new URL("../dist/out/index.js", import.meta.url);+ const result = spawnSync(process.execPath, [entry.pathname], {+ input: 'throw new Error("single-error-probe")\n',+ encoding: "utf8",+ });++ assert.equal(result.status, 1);+ assert.equal(result.stderr.match(/single-error-probe/g)?.length, 1);+});diff --git a/package/ego-browser/src/run.ts b/package/ego-browser/src/run.tsindex 21bce66..122b3fe 100644--- a/package/ego-browser/src/run.ts+++ b/package/ego-browser/src/run.ts@@ -6,6 +6,7 @@ import {import { formatCliLogValue } from "./format.js";import * as helpers from "./helpers.js";+import { addPageContextHint } from "./page-context-guard.js";import {bufferOutput,createRoundConsole,@@ -128,7 +129,7 @@ async function execute(code: string, stdout: WritableLike) {// The thrown Error surfaces the hard-stop message on its own, so flush as a thrown// completion (drop the buffer, stay silent) and let it propagate.flushSink(stdout, true);- throw error;+ throw addPageContextHint(error);}flushSink(stdout, false);}diff --git a/package/ego-browser/src/sdk-lifecycle.test.mjs b/package/ego-browser/src/sdk-lifecycle.test.mjsindex 1000182..f49098c 100644--- a/package/ego-browser/src/sdk-lifecycle.test.mjs+++ b/package/ego-browser/src/sdk-lifecycle.test.mjs@@ -49,3 +49,25 @@ test("disposeEgoSdk releases native callbacks and rejects pending CDP work", ()assert.equal(result.status, 0, result.stderr);assert.match(result.stderr, /sdk lifecycle ok/);});++test("the embedded SDK explains that document belongs inside Page.evaluate", () => {+ const sdkUrl = new URL("../dist/src/index.js", import.meta.url).href;+ const script = `+ globalThis.ego = {};+ await import(${JSON.stringify(sdkUrl)});+ try {+ document.body;+ throw new Error("document guard did not run");+ } catch (error) {+ if (!/document is not defined/i.test(error.message)) throw error;+ if (!/page\\.evaluate\\(\\)/i.test(error.message)) throw error;+ }+ `;+ const result = spawnSync(+ process.execPath,+ ["--input-type=module", "--eval", script],+ { encoding: "utf8" },+ );++ assert.equal(result.status, 0, result.stderr);+});diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.mdindex 25c5789..29b96eb 100644--- a/skills/ego-browser/SKILL.md+++ b/skills/ego-browser/SKILL.md@@ -126,6 +126,10 @@ Selector actions require exactly one match. Unquoted text normalizes whitespace,ignores case, and matches a substring; quoted text such as`text="Save changes"` is exact and case-sensitive.+When a selector identifies a wrapper, `focus()` and `press()` may use its+interactive ancestor or unique editable descendant; `fill()` and+`setInputFiles()` only continue to a unique compatible control.+Snapshot node names are accessibility roles. Use a current ref for an immediateaction and a generated locator for reuse. When a useful node has no ref,construct a selector from its role, text, or surrounding context. CSS searches@@ -152,7 +156,15 @@ keyboard names and `+`-separated chords follow Playwright syntax. Use`ControlOrMeta` for portable shortcuts and verify the resulting page state.`keyboard.paste()` sends the native paste shortcut and then restores the user's-clipboard. The focused page decides how to interpret tabs and newlines.+clipboard. Pass `{ text, html }` when a rich editor needs structured clipboard+content; `text` is the plain-text fallback.++```js+await page.keyboard.paste({+ text: "Name\tStatus",+ html: "<table><tr><td>Name</td><td>Status</td></tr></table>",+});+```For rich-text editors and editable grids, validate a small edit and its resultbefore repeating it at scale.diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.mdindex 28ba350..7839825 100644--- a/skills/ego-browser/references/api.md+++ b/skills/ego-browser/references/api.md@@ -37,37 +37,37 @@ High-level Page actions return a receipt that may contain `popups` or a synchron## Page-| API | Options | Purpose |-| --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |-| `page.label` | — | Durable Page label used to restore the tab across rounds. |-| `page.spaceId` | — | Numeric identifier of the Page's task space. |-| `page.openedBy` | — | Conservative origin attribution for this Page. |-| `page.targetId` | — | Internal browser target identifier for advanced Target-domain CDP only. |-| `await page.goto(url, { referer?, timeout?, waitUntil? })` | `referer` — HTTP Referer header for the navigation.<br>`timeout` — Maximum duration in milliseconds.<br>`waitUntil` (commit, domcontentloaded, load, networkidle) — Completion state; defaults to load. networkidle requires 500ms without network activity. | Navigate this Page in place. |-| `await page.snapshot({ scope?, includeActionMarks?, includeStableLocator? })` | `scope` (full_page, only_within_viewport) — Snapshot scope; defaults to only_within_viewport.<br>`includeActionMarks` — Include action marks.<br>`includeStableLocator` — Include stable locators. | Return a semantic snapshot of the current viewport with Page provenance. |-| `await page.screenshot({ path?, fullPage?, clip?, raw? })` | `path` — Output path; missing parent directories are created.<br>`fullPage` — Capture the full scrollable page.<br>`clip` — CSS-pixel clipping rectangle.<br>`raw` — Bypass device-pixel-ratio correction. | Capture this Page to a PNG file. |-| `await page.url()` | — | Read this Page's current URL. |-| `await page.waitForURL(urlOrRegExp, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for an exact URL or regular-expression match. |-| `await page.waitForTimeout(timeout)` | — | Wait a fixed number of milliseconds without activating this Page. |-| `await page.title()` | — | Read this Page's current title. |-| `await page.info()` | — | Read URL, title, viewport, scroll, and dialog state. |-| `await page.evaluate(fnOrString, argument?)` | — | Run JavaScript in this Page with JSON-serializable data. |-| `await page.fetch(url, options?)` | `timeout` — Maximum duration in milliseconds.<br>`method` — HTTP method.<br>`headers` — Request headers.<br>`body` — Request body.<br>`cache` (default, no-store, reload, no-cache, force-cache, only-if-cached) — Fetch cache mode.<br>`credentials` (omit, same-origin, include) — Fetch credentials mode.<br>`integrity` — Subresource integrity value.<br>`keepalive` — Allow the request to outlive the page.<br>`mode` (cors, no-cors, same-origin) — Fetch request mode.<br>`redirect` (follow, error, manual) — Redirect handling mode.<br>`referrer` — Request referrer.<br>`referrerPolicy` — Request referrer policy. | Run window.fetch in this Page and return a structured response. |-| `await page.cdp(method, params?, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Send a CDP command through this Page's target session. |-| `await page.waitForSelector(selector, { timeout?, state? })` | `timeout` — Maximum duration in milliseconds.<br>`state` (attached, detached, visible, hidden) — Required element state. | Wait for an element state in this Page. |-| `await page.waitForLoadState(state, { timeout?, idleMs? })` | `timeout` — Maximum duration in milliseconds.<br>`idleMs` — Required network-idle window in milliseconds. | Wait for DOM content, load, or network-idle state. |-| `await page.events()` | — | Read and clear CDP events buffered for this Page. |-| `await page.click(selector, { button?, clickCount?, delay?, position?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Click an element with native CDP input. |-| `await page.dblclick(selector, { button?, delay?, position?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Double-click an element with native CDP input. |-| `await page.hover(selector, { position?, force?, timeout? })` | `position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Move the mouse over an element. |-| `await page.dragAndDrop(source, target, { button?, sourcePosition?, targetPosition?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`sourcePosition` — CSS-pixel offset from the element's top-left corner.<br>`targetPosition` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Drag from one element to another. |-| `await page.fill(selector, value, { clearFirst?, timeout? })` | `clearFirst` — Clear the current value before filling.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Focus and fill an input-like element, then verify its value. |-| `await page.focus(selector, { timeout? })` | `timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Resolve one element and focus it. |-| `await page.press(selector, chord, { delay?, timeout? })` | `delay` — Input delay in milliseconds.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Focus one element and press a key or shortcut chord. |-| `await page.setInputFiles(selector, pathOrPaths)` | — | Set files on a file input without opening the system chooser. |-| `page.waitForFileChooser({ timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for a dynamically created file chooser. |-| `await page.scrollBy(deltaY, { deltaX?, behavior? })` | `deltaX` — Horizontal CSS-pixel delta.<br>`behavior` (auto, instant, smooth) — Scroll behavior. | Scroll this Page by CSS-pixel deltas. |-| `await page.close()` | — | Close this Page after confirming its tab disappeared. |+| API | Options | Purpose |+| --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |+| `page.label` | — | Durable Page label used to restore the tab across rounds. |+| `page.spaceId` | — | Numeric identifier of the Page's task space. |+| `page.openedBy` | — | Conservative origin attribution for this Page. |+| `page.targetId` | — | Internal browser target identifier for advanced Target-domain CDP only. |+| `await page.goto(url, { referer?, timeout?, waitUntil? })` | `referer` — HTTP Referer header for the navigation.<br>`timeout` — Maximum duration in milliseconds.<br>`waitUntil` (commit, domcontentloaded, load, networkidle) — Completion state; defaults to load. networkidle requires 500ms without network activity. | Navigate this Page in place. |+| `await page.snapshot({ scope?, includeActionMarks?, includeStableLocator? })` | `scope` (full_page, only_within_viewport) — Snapshot scope; defaults to only_within_viewport.<br>`includeActionMarks` — Include action marks.<br>`includeStableLocator` — Include stable locators. | Return a semantic snapshot of the current viewport with Page provenance. |+| `await page.screenshot({ path?, fullPage?, clip?, raw? })` | `path` — Output path; missing parent directories are created.<br>`fullPage` — Capture the full scrollable page.<br>`clip` — CSS-pixel clipping rectangle.<br>`raw` — Bypass device-pixel-ratio correction. | Capture this Page to a PNG file. |+| `await page.url()` | — | Read this Page's current URL. |+| `await page.waitForURL(urlOrRegExp, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for an exact URL or regular-expression match. |+| `await page.waitForTimeout(timeout)` | — | Wait a fixed number of milliseconds without activating this Page. |+| `await page.title()` | — | Read this Page's current title. |+| `await page.info()` | — | Read URL, title, viewport, scroll, and dialog state. |+| `await page.evaluate(fnOrString, argument?)` | — | Run JavaScript in this Page with JSON-serializable data. |+| `await page.fetch(url, options?)` | `timeout` — Maximum duration in milliseconds.<br>`method` — HTTP method.<br>`headers` — Request headers.<br>`body` — Request body.<br>`cache` (default, no-store, reload, no-cache, force-cache, only-if-cached) — Fetch cache mode.<br>`credentials` (omit, same-origin, include) — Fetch credentials mode.<br>`integrity` — Subresource integrity value.<br>`keepalive` — Allow the request to outlive the page.<br>`mode` (cors, no-cors, same-origin) — Fetch request mode.<br>`redirect` (follow, error, manual) — Redirect handling mode.<br>`referrer` — Request referrer.<br>`referrerPolicy` — Request referrer policy. | Run window.fetch in this Page and return a structured response. |+| `await page.cdp(method, params?, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Send a CDP command through this Page's target session. |+| `await page.waitForSelector(selector, { timeout?, state? })` | `timeout` — Maximum duration in milliseconds.<br>`state` (attached, detached, visible, hidden) — Required element state. | Wait for an element state in this Page. |+| `await page.waitForLoadState(state, { timeout?, idleMs? })` | `timeout` — Maximum duration in milliseconds.<br>`idleMs` — Required network-idle window in milliseconds. | Wait for DOM content, load, or network-idle state. |+| `await page.events()` | — | Read and clear CDP events buffered for this Page. |+| `await page.click(selector, { button?, clickCount?, delay?, position?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Click an element with native CDP input. |+| `await page.dblclick(selector, { button?, delay?, position?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Double-click an element with native CDP input. |+| `await page.hover(selector, { position?, force?, timeout? })` | `position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Move the mouse over an element. |+| `await page.dragAndDrop(source, target, { button?, sourcePosition?, targetPosition?, force?, timeout? })` | `button` (left, middle, right) — Mouse button.<br>`sourcePosition` — CSS-pixel offset from the element's top-left corner.<br>`targetPosition` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Drag from one element to another. |+| `await page.fill(selector, value, { clearFirst?, timeout? })` | `clearFirst` — Clear the current value before filling.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Fill the selected field, its editing host, or its unique fillable descendant, then verify the value. |+| `await page.focus(selector, { timeout? })` | `timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Focus the element, its nearest interactive ancestor, or its unique editable descendant. |+| `await page.press(selector, chord, { delay?, timeout? })` | `delay` — Input delay in milliseconds.<br>`timeout` — Maximum actionability wait in milliseconds; defaults to 3000. | Focus one element and press a key or shortcut chord. |+| `await page.setInputFiles(selector, pathOrPaths)` | — | Set files on a file input resolved from the input, its label, or a unique descendant. |+| `page.waitForFileChooser({ timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for a dynamically created file chooser. |+| `await page.scrollBy(deltaY, { deltaX?, behavior? })` | `deltaX` — Horizontal CSS-pixel delta.<br>`behavior` (auto, instant, smooth) — Scroll behavior. | Scroll this Page by CSS-pixel deltas. |+| `await page.close()` | — | Close this Page after confirming its tab disappeared. |## Page.mouse@@ -81,11 +81,11 @@ High-level Page actions return a receipt that may contain `popups` or a synchron## Page.keyboard-| API | Options | Purpose |-| ---------------------------------------------- | -------------------------------------- | ---------------------------------------------------------------------------------- |-| `await page.keyboard.down(key)` | — | Press and hold a keyboard key. |-| `await page.keyboard.up(key)` | — | Release a keyboard key. |-| `await page.keyboard.press(chord, { delay? })` | `delay` — Input delay in milliseconds. | Press and release a key or portable shortcut chord. |-| `await page.keyboard.type(text, { delay? })` | `delay` — Input delay in milliseconds. | Type text using physical keys where possible. |-| `await page.keyboard.insertText(text)` | — | Insert text without synthesizing key presses. |-| `await page.keyboard.paste(text)` | — | Send native paste and restore the clipboard; the focused page interprets the text. |+| API | Options | Purpose |+| ---------------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------- |+| `await page.keyboard.down(key)` | — | Press and hold a keyboard key. |+| `await page.keyboard.up(key)` | — | Release a keyboard key. |+| `await page.keyboard.press(chord, { delay? })` | `delay` — Input delay in milliseconds. | Press and release a key or portable shortcut chord. |+| `await page.keyboard.type(text, { delay? })` | `delay` — Input delay in milliseconds. | Type text using physical keys where possible. |+| `await page.keyboard.insertText(text)` | — | Insert text without synthesizing key presses. |+| `await page.keyboard.paste(textOrContent)` | — | Send native paste with a string or { text, html? }, then restore the clipboard. |