Skip to content

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.

fix(ego-browser): unify driver selector resolution; fix fillInput on email/number

0x0d34d421aa5bd
diff --git a/package/ego-browser/artifacts/ego-browser/index.js b/package/ego-browser/artifacts/ego-browser/index.js
index 501ed38..07911f9 100755
--- a/package/ego-browser/artifacts/ego-browser/index.js
+++ b/package/ego-browser/artifacts/ego-browser/index.js
@@ -7920,6 +7920,19 @@ var pointer = /*#__PURE__*/Object.freeze({
scrollToBottomUntil: scrollToBottomUntil
});
+/**
+ * Resolve any selector form to a CDP Runtime objectId handle.
+ * Accepts @ref / ref=N, loc=css:/loc=role:/loc=href:, xpath=, and raw CSS —
+ * the same surface as the pointer/observe helpers, via the unified resolver.
+ * Refreshes the RefMap on demand when the input is a ref and the map is empty.
+ * @param {string} selectorOrRef Selector or ref string.
+ * @returns {Promise<{objectId: string, sessionId?: string}>}
+ */
+async function resolveHandle(selectorOrRef) {
+ await ensureRefMapForRef(selectorOrRef);
+ return resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selectorOrRef);
+}
+
/**
* Sleep for a fixed number of seconds.
* @param {number} [seconds=1.0] Seconds to wait.
@@ -7938,7 +7951,7 @@ async function waitForLoad(options = {}) {
}
/**
* Wait until an element exists, optionally requiring visibility.
- * @param {string} selector CSS selector or @ref to poll.
+ * @param {string} selector CSS selector / @ref / loc= / xpath= to poll.
* @param {{timeout?: number, visible?: boolean}} [options]
* @returns {Promise<boolean>} True when found before timeout.
*/
@@ -7946,36 +7959,23 @@ async function waitForElement(selector, options = {}) {
const timeout = options.timeout ?? 10.0;
const visible = options.visible ?? false;
const deadline = state.now() + timeout * 1000;
- if (parseRef(selector)) {
- await ensureRefMapForRef(selector);
- const visibilityFn = "function(){if(typeof this.checkVisibility==='function')return this.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});const s=getComputedStyle(this);return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0';}";
- while (state.now() < deadline) {
- try {
- const { objectId, sessionId } = await resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selector);
- if (!visible)
- return true;
- const response = await cdp("Runtime.callFunctionOn", {
- functionDeclaration: visibilityFn,
- objectId,
- returnByValue: true,
- awaitPromise: false
- }, sessionId);
- if (response.result?.value)
- return true;
- }
- catch {
- // ref not yet resolvable; keep polling.
- }
- await state.sleep(300);
- }
- return false;
- }
- const check = visible
- ? `(()=>{const e=document.querySelector(${JSON.stringify(selector)});if(!e)return false;if(typeof e.checkVisibility==='function')return e.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});const s=getComputedStyle(e);return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0'})()`
- : `!!document.querySelector(${JSON.stringify(selector)})`;
+ const visibilityFn = "function(){if(typeof this.checkVisibility==='function')return this.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});const s=getComputedStyle(this);return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0';}";
while (state.now() < deadline) {
- if (await js(check)) {
- return true;
+ try {
+ const { objectId, sessionId } = await resolveHandle(selector);
+ if (!visible)
+ return true;
+ const response = await cdp("Runtime.callFunctionOn", {
+ functionDeclaration: visibilityFn,
+ objectId,
+ returnByValue: true,
+ awaitPromise: false
+ }, sessionId);
+ if (response.result?.value)
+ return true;
+ }
+ catch {
+ // element not yet resolvable; keep polling.
}
await state.sleep(300);
}
@@ -8075,7 +8075,7 @@ async function typeText(text) {
}
/**
* Focus an input, optionally clear it, type text, and fire input/change events.
- * @param {string} selector CSS selector or @ref for the input-like element.
+ * @param {string} selector CSS selector / @ref / loc= / xpath= for the input-like element.
* @param {string} text Text to write.
* @param {{clearFirst?: boolean, timeout?: number}} [options]
* @returns {Promise<void>}
@@ -8086,48 +8086,33 @@ async function fillInput(selector, text, options = {}) {
if (timeout > 0 && !await waitForElement(selector, { timeout })) {
throw new Error(`fillInput: element not found: ${JSON.stringify(selector)}`);
}
- if (parseRef(selector)) {
- await ensureRefMapForRef(selector);
- const { objectId, sessionId } = await resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selector);
- await cdp("Runtime.callFunctionOn", {
- functionDeclaration: "function(){this.focus(); if(typeof this.select==='function') this.select();}",
- objectId,
- returnByValue: true,
- awaitPromise: false
- }, sessionId);
- if (clearFirst) {
- await cdp("Runtime.callFunctionOn", {
- functionDeclaration: "function(){const v=this.value??this.textContent??''; if(typeof this.setSelectionRange==='function'){this.setSelectionRange(0,v.length);return;} if(typeof this.select==='function')this.select();}",
- objectId,
- returnByValue: true,
- awaitPromise: false
- }, sessionId);
- await pressKey("Backspace");
- }
- await cdp("Input.insertText", { text }, sessionId);
+ const { objectId, sessionId } = await resolveHandle(selector);
+ await cdp("Runtime.callFunctionOn", {
+ functionDeclaration: "function(){this.focus(); if(typeof this.select==='function') this.select();}",
+ objectId,
+ returnByValue: true,
+ awaitPromise: false
+ }, sessionId);
+ if (clearFirst) {
await cdp("Runtime.callFunctionOn", {
- functionDeclaration: "function(){this.dispatchEvent(new Event('input',{bubbles:true})); this.dispatchEvent(new Event('change',{bubbles:true}));}",
+ functionDeclaration: "function(){this.value=''; this.dispatchEvent(new Event('input',{bubbles:true}));}",
objectId,
returnByValue: true,
awaitPromise: false
}, sessionId);
- return;
}
- const focused = await js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)});if(!e)return false;e.focus();if(typeof e.select==='function')e.select();return true;})()`);
- if (!focused) {
- throw new Error(`fillInput: element not found: ${JSON.stringify(selector)}`);
- }
- if (clearFirst) {
- await js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)});if(!e)return;const value=e.value??e.textContent??'';if(typeof e.setSelectionRange==='function'){e.setSelectionRange(0,value.length);return;}if(typeof e.select==='function')e.select();})()`);
- await pressKey("Backspace");
- }
- await typeText(text);
- await js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)});if(!e)return;e.dispatchEvent(new Event('input',{bubbles:true}));e.dispatchEvent(new Event('change',{bubbles:true}));})()`);
+ await cdp("Input.insertText", { text }, sessionId);
+ await cdp("Runtime.callFunctionOn", {
+ functionDeclaration: "function(){this.dispatchEvent(new Event('input',{bubbles:true})); this.dispatchEvent(new Event('change',{bubbles:true}));}",
+ objectId,
+ returnByValue: true,
+ awaitPromise: false
+ }, sessionId);
}
/**
* Focus an element and dispatch a DOM KeyboardEvent in page JavaScript.
* Note: dispatched event has isTrusted=false; some frameworks ignore it (see docs/issues/dispatchKey-synthetic-keyboard-event.md).
- * @param {string} selector CSS selector or @ref for the target element.
+ * @param {string} selector CSS selector / @ref / loc= / xpath= for the target element.
* @param {string} [key="Enter"] Event key.
* @param {"keydown"|"keypress"|"keyup"|string} [event="keypress"] Event type.
* @returns {Promise<void>}
@@ -8135,19 +8120,15 @@ async function fillInput(selector, text, options = {}) {
async function dispatchKey(selector, key = "Enter", event = "keypress") {
const keyCodes = { Enter: 13, Tab: 9, Escape: 27, Backspace: 8, " ": 32, ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40 };
const keyCode = keyCodes[key] || (key.length === 1 ? key.codePointAt(0) : 0);
- if (parseRef(selector)) {
- await ensureRefMapForRef(selector);
- const { objectId, sessionId } = await resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selector);
- await cdp("Runtime.callFunctionOn", {
- functionDeclaration: "function(keyCode, key, event){this.focus(); this.dispatchEvent(new KeyboardEvent(event,{key,code:key,keyCode,which:keyCode,bubbles:true}));}",
- objectId,
- arguments: [{ value: keyCode }, { value: key }, { value: event }],
- returnByValue: true,
- awaitPromise: false
- }, sessionId);
- return;
- }
- await js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)});if(e){e.focus();e.dispatchEvent(new KeyboardEvent(${JSON.stringify(event)},{key:${JSON.stringify(key)},code:${JSON.stringify(key)},keyCode:${keyCode},which:${keyCode},bubbles:true}));}})()`);
+ const { code } = keyDefinition(key);
+ const { objectId, sessionId } = await resolveHandle(selector);
+ await cdp("Runtime.callFunctionOn", {
+ functionDeclaration: "function(keyCode, key, code, event){this.focus(); this.dispatchEvent(new KeyboardEvent(event,{key,code,keyCode,which:keyCode,bubbles:true}));}",
+ objectId,
+ arguments: [{ value: keyCode }, { value: key }, { value: code }, { value: event }],
+ returnByValue: true,
+ awaitPromise: false
+ }, sessionId);
}
var keyboard = /*#__PURE__*/Object.freeze({
@@ -8160,24 +8141,14 @@ var keyboard = /*#__PURE__*/Object.freeze({
/**
* Set files on a file input.
- * @param {string} selector CSS selector or @ref for an input[type=file].
+ * @param {string} selector CSS selector / @ref / loc= / xpath= for an input[type=file].
* @param {string|string[]} path Absolute file path or paths to upload.
* @returns {Promise<void>}
*/
async function uploadFile(selector, path) {
const files = Array.isArray(path) ? path : [path];
- if (parseRef(selector)) {
- await ensureRefMapForRef(selector);
- const { objectId, sessionId } = await resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selector);
- await cdp("DOM.setFileInputFiles", { files, objectId }, sessionId);
- return;
- }
- const doc = await cdp("DOM.getDocument", { depth: -1 });
- const nodeId = (await cdp("DOM.querySelector", { nodeId: doc.root.nodeId, selector })).nodeId;
- if (!nodeId) {
- throw new Error(`no element for ${selector}`);
- }
- await cdp("DOM.setFileInputFiles", { files, nodeId });
+ const { objectId, sessionId } = await resolveHandle(selector);
+ await cdp("DOM.setFileInputFiles", { files, objectId }, sessionId);
}
var files = /*#__PURE__*/Object.freeze({
diff --git a/package/ego-browser/src/driver/element-ops.ts b/package/ego-browser/src/driver/element-ops.ts
new file mode 100644
index 0000000..21c3395
--- /dev/null
+++ b/package/ego-browser/src/driver/element-ops.ts
@@ -0,0 +1,36 @@
+import { cdp } from "../cdp-eval.js";
+import { browserRefMap, ensureRefMapForRef } from "../ref-state.js";
+import { resolveElementObjectId } from "../element-resolver.js";
+
+/**
+ * Resolve any selector form to a CDP Runtime objectId handle.
+ * Accepts @ref / ref=N, loc=css:/loc=role:/loc=href:, xpath=, and raw CSS —
+ * the same surface as the pointer/observe helpers, via the unified resolver.
+ * Refreshes the RefMap on demand when the input is a ref and the map is empty.
+ * @param {string} selectorOrRef Selector or ref string.
+ * @returns {Promise<{objectId: string, sessionId?: string}>}
+ */
+export async function resolveHandle(selectorOrRef) {
+ await ensureRefMapForRef(selectorOrRef);
+ return resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selectorOrRef);
+}
+
+/**
+ * Resolve an element and call a function on it via Runtime.callFunctionOn,
+ * with the element bound as `this`.
+ * @param {string} selectorOrRef Selector or ref string.
+ * @param {string} functionDeclaration Function source whose `this` is the element.
+ * @param {Array<unknown>} [args=[]] Arguments passed by value.
+ * @returns {Promise<{result: any, objectId: string, sessionId?: string}>}
+ */
+export async function resolveAndCall(selectorOrRef, functionDeclaration, args = []) {
+ const { objectId, sessionId } = await resolveHandle(selectorOrRef);
+ const result = await cdp("Runtime.callFunctionOn", {
+ functionDeclaration,
+ objectId,
+ arguments: args.map((value) => ({ value })),
+ returnByValue: true,
+ awaitPromise: false
+ }, sessionId);
+ return { result, objectId, sessionId };
+}
diff --git a/package/ego-browser/src/driver/files.ts b/package/ego-browser/src/driver/files.ts
index 45c023d..7251de9 100644
--- a/package/ego-browser/src/driver/files.ts
+++ b/package/ego-browser/src/driver/files.ts
@@ -1,26 +1,14 @@
import { cdp } from "../cdp-eval.js";
-import { parseRef } from "../ref-map.js";
-import { browserRefMap, ensureRefMapForRef } from "../ref-state.js";
-import { resolveElementObjectId } from "../element-resolver.js";
+import { resolveHandle } from "./element-ops.js";
/**
* Set files on a file input.
- * @param {string} selector CSS selector or @ref for an input[type=file].
+ * @param {string} selector CSS selector / @ref / loc= / xpath= for an input[type=file].
* @param {string|string[]} path Absolute file path or paths to upload.
* @returns {Promise<void>}
*/
export async function uploadFile(selector, path) {
const files = Array.isArray(path) ? path : [path];
- if (parseRef(selector)) {
- await ensureRefMapForRef(selector);
- const { objectId, sessionId } = await resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selector);
- await cdp("DOM.setFileInputFiles", { files, objectId }, sessionId);
- return;
- }
- const doc = await cdp("DOM.getDocument", { depth: -1 });
- const nodeId = (await cdp("DOM.querySelector", { nodeId: doc.root.nodeId, selector })).nodeId;
- if (!nodeId) {
- throw new Error(`no element for ${selector}`);
- }
- await cdp("DOM.setFileInputFiles", { files, nodeId });
+ const { objectId, sessionId } = await resolveHandle(selector);
+ await cdp("DOM.setFileInputFiles", { files, objectId }, sessionId);
}
diff --git a/package/ego-browser/src/driver/keyboard.ts b/package/ego-browser/src/driver/keyboard.ts
index df74725..dd7770b 100644
--- a/package/ego-browser/src/driver/keyboard.ts
+++ b/package/ego-browser/src/driver/keyboard.ts
@@ -1,7 +1,5 @@
-import { cdp, js } from "../cdp-eval.js";
-import { parseRef } from "../ref-map.js";
-import { browserRefMap, ensureRefMapForRef } from "../ref-state.js";
-import { resolveElementObjectId } from "../element-resolver.js";
+import { cdp } from "../cdp-eval.js";
+import { resolveHandle, resolveAndCall } from "./element-ops.js";
import { waitForElement } from "./waits.js";
type FillInputOptions = {
@@ -65,7 +63,7 @@ export async function typeText(text) {
/**
* Focus an input, optionally clear it, type text, and fire input/change events.
- * @param {string} selector CSS selector or @ref for the input-like element.
+ * @param {string} selector CSS selector / @ref / loc= / xpath= for the input-like element.
* @param {string} text Text to write.
* @param {{clearFirst?: boolean, timeout?: number}} [options]
* @returns {Promise<void>}
@@ -76,49 +74,34 @@ export async function fillInput(selector, text, options: FillInputOptions = {})
if (timeout > 0 && !await waitForElement(selector, { timeout })) {
throw new Error(`fillInput: element not found: ${JSON.stringify(selector)}`);
}
- if (parseRef(selector)) {
- await ensureRefMapForRef(selector);
- const { objectId, sessionId } = await resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selector);
- await cdp("Runtime.callFunctionOn", {
- functionDeclaration: "function(){this.focus(); if(typeof this.select==='function') this.select();}",
- objectId,
- returnByValue: true,
- awaitPromise: false
- }, sessionId);
- if (clearFirst) {
- await cdp("Runtime.callFunctionOn", {
- functionDeclaration: "function(){const v=this.value??this.textContent??''; if(typeof this.setSelectionRange==='function'){this.setSelectionRange(0,v.length);return;} if(typeof this.select==='function')this.select();}",
- objectId,
- returnByValue: true,
- awaitPromise: false
- }, sessionId);
- await pressKey("Backspace");
- }
- await cdp("Input.insertText", { text }, sessionId);
+ const { objectId, sessionId } = await resolveHandle(selector);
+ await cdp("Runtime.callFunctionOn", {
+ functionDeclaration: "function(){this.focus(); if(typeof this.select==='function') this.select();}",
+ objectId,
+ returnByValue: true,
+ awaitPromise: false
+ }, sessionId);
+ if (clearFirst) {
await cdp("Runtime.callFunctionOn", {
- functionDeclaration: "function(){this.dispatchEvent(new Event('input',{bubbles:true})); this.dispatchEvent(new Event('change',{bubbles:true}));}",
+ functionDeclaration: "function(){this.value=''; this.dispatchEvent(new Event('input',{bubbles:true}));}",
objectId,
returnByValue: true,
awaitPromise: false
}, sessionId);
- return;
- }
- const focused = await js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)});if(!e)return false;e.focus();if(typeof e.select==='function')e.select();return true;})()`);
- if (!focused) {
- throw new Error(`fillInput: element not found: ${JSON.stringify(selector)}`);
}
- if (clearFirst) {
- await js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)});if(!e)return;const value=e.value??e.textContent??'';if(typeof e.setSelectionRange==='function'){e.setSelectionRange(0,value.length);return;}if(typeof e.select==='function')e.select();})()`);
- await pressKey("Backspace");
- }
- await typeText(text);
- await js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)});if(!e)return;e.dispatchEvent(new Event('input',{bubbles:true}));e.dispatchEvent(new Event('change',{bubbles:true}));})()`);
+ await cdp("Input.insertText", { text }, sessionId);
+ await cdp("Runtime.callFunctionOn", {
+ functionDeclaration: "function(){this.dispatchEvent(new Event('input',{bubbles:true})); this.dispatchEvent(new Event('change',{bubbles:true}));}",
+ objectId,
+ returnByValue: true,
+ awaitPromise: false
+ }, sessionId);
}
/**
* Focus an element and dispatch a DOM KeyboardEvent in page JavaScript.
* Note: dispatched event has isTrusted=false; some frameworks ignore it (see docs/issues/dispatchKey-synthetic-keyboard-event.md).
- * @param {string} selector CSS selector or @ref for the target element.
+ * @param {string} selector CSS selector / @ref / loc= / xpath= for the target element.
* @param {string} [key="Enter"] Event key.
* @param {"keydown"|"keypress"|"keyup"|string} [event="keypress"] Event type.
* @returns {Promise<void>}
@@ -126,17 +109,10 @@ export async function fillInput(selector, text, options: FillInputOptions = {})
export async function dispatchKey(selector, key = "Enter", event = "keypress") {
const keyCodes = { Enter: 13, Tab: 9, Escape: 27, Backspace: 8, " ": 32, ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40 };
const keyCode = keyCodes[key] || (key.length === 1 ? key.codePointAt(0) : 0);
- if (parseRef(selector)) {
- await ensureRefMapForRef(selector);
- const { objectId, sessionId } = await resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selector);
- await cdp("Runtime.callFunctionOn", {
- functionDeclaration: "function(keyCode, key, event){this.focus(); this.dispatchEvent(new KeyboardEvent(event,{key,code:key,keyCode,which:keyCode,bubbles:true}));}",
- objectId,
- arguments: [{ value: keyCode }, { value: key }, { value: event }],
- returnByValue: true,
- awaitPromise: false
- }, sessionId);
- return;
- }
- await js(`(()=>{const e=document.querySelector(${JSON.stringify(selector)});if(e){e.focus();e.dispatchEvent(new KeyboardEvent(${JSON.stringify(event)},{key:${JSON.stringify(key)},code:${JSON.stringify(key)},keyCode:${keyCode},which:${keyCode},bubbles:true}));}})()`);
+ const { code } = keyDefinition(key);
+ await resolveAndCall(
+ selector,
+ "function(keyCode, key, code, event){this.focus(); this.dispatchEvent(new KeyboardEvent(event,{key,code,keyCode,which:keyCode,bubbles:true}));}",
+ [keyCode, key, code, event]
+ );
}
diff --git a/package/ego-browser/src/driver/waits.ts b/package/ego-browser/src/driver/waits.ts
index bf514e8..f4e8485 100644
--- a/package/ego-browser/src/driver/waits.ts
+++ b/package/ego-browser/src/driver/waits.ts
@@ -1,8 +1,6 @@
import { state } from "../state.js";
-import { cdp, js } from "../cdp-eval.js";
-import { parseRef } from "../ref-map.js";
-import { browserRefMap, ensureRefMapForRef } from "../ref-state.js";
-import { resolveElementObjectId } from "../element-resolver.js";
+import { cdp } from "../cdp-eval.js";
+import { resolveHandle } from "./element-ops.js";
import { type WaitForLoadOptions, waitForDocumentLoad } from "./load.js";
import { drainEvents } from "./observe.js";
@@ -36,7 +34,7 @@ export async function waitForLoad(options: WaitForLoadOptions = {}) {
/**
* Wait until an element exists, optionally requiring visibility.
- * @param {string} selector CSS selector or @ref to poll.
+ * @param {string} selector CSS selector / @ref / loc= / xpath= to poll.
* @param {{timeout?: number, visible?: boolean}} [options]
* @returns {Promise<boolean>} True when found before timeout.
*/
@@ -44,33 +42,20 @@ export async function waitForElement(selector: string, options: WaitForElementOp
const timeout = options.timeout ?? 10.0;
const visible = options.visible ?? false;
const deadline = state.now() + timeout * 1000;
- if (parseRef(selector)) {
- await ensureRefMapForRef(selector);
- const visibilityFn = "function(){if(typeof this.checkVisibility==='function')return this.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});const s=getComputedStyle(this);return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0';}";
- while (state.now() < deadline) {
- try {
- const { objectId, sessionId } = await resolveElementObjectId({ sendRaw: cdp }, undefined, browserRefMap, selector);
- if (!visible) return true;
- const response = await cdp("Runtime.callFunctionOn", {
- functionDeclaration: visibilityFn,
- objectId,
- returnByValue: true,
- awaitPromise: false
- }, sessionId);
- if (response.result?.value) return true;
- } catch {
- // ref not yet resolvable; keep polling.
- }
- await state.sleep(300);
- }
- return false;
- }
- const check = visible
- ? `(()=>{const e=document.querySelector(${JSON.stringify(selector)});if(!e)return false;if(typeof e.checkVisibility==='function')return e.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});const s=getComputedStyle(e);return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0'})()`
- : `!!document.querySelector(${JSON.stringify(selector)})`;
+ const visibilityFn = "function(){if(typeof this.checkVisibility==='function')return this.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});const s=getComputedStyle(this);return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0';}";
while (state.now() < deadline) {
- if (await js(check)) {
- return true;
+ try {
+ const { objectId, sessionId } = await resolveHandle(selector);
+ if (!visible) return true;
+ const response = await cdp("Runtime.callFunctionOn", {
+ functionDeclaration: visibilityFn,
+ objectId,
+ returnByValue: true,
+ awaitPromise: false
+ }, sessionId);
+ if (response.result?.value) return true;
+ } catch {
+ // element not yet resolvable; keep polling.
}
await state.sleep(300);
}
diff --git a/package/ego-browser/test/browser-e2e.test.js b/package/ego-browser/test/browser-e2e.test.js
index 67b8429..712a4a4 100644
--- a/package/ego-browser/test/browser-e2e.test.js
+++ b/package/ego-browser/test/browser-e2e.test.js
@@ -104,3 +104,53 @@ test("elementEval: arrow (el)=>el.X, (el,arg)=>el[arg], and legacy function(){th
assert.equal(payload.arrowWithArg, "H1", "arrow (el, prop)=>el[prop] must forward args after el");
assert.equal(payload.legacyThisForm, "H1", "legacy function(){return this.tagName} must remain bound to el");
});
+
+test("fillInput writes into email/number/text inputs without InvalidStateError (symptom A)", e2eSkip, () => {
+ const script = `
+ const name = 'e2e-fill-input';
+ await useOrCreateTaskSpace(name);
+ const html = '<input name="email" type="email" value="[email protected]">'
+ + '<input name="number" type="number" value="123">'
+ + '<input name="text" type="text" value="oldtext">';
+ await gotoAndWait('data:text/html;charset=utf-8,' + encodeURIComponent(html), { wait: true, timeout: 20 });
+
+ await fillInput('input[name="email"]', '[email protected]');
+ await fillInput('input[name="number"]', '456');
+ await fillInput('input[name="text"]', 'newtext');
+
+ const email = await elementEval('input[name="email"]', (el) => el.value);
+ const number = await elementEval('input[name="number"]', (el) => el.value);
+ const text = await elementEval('input[name="text"]', (el) => el.value);
+
+ await completeTaskSpace(name, { keep: false });
+ cliLog(JSON.stringify({ email, number, text }));
+ `;
+ const result = runScript(script);
+ const payload = lastJsonLine(result.stderr);
+ assert.equal(payload.email, "[email protected]", "fillInput must write into type=email without InvalidStateError");
+ assert.equal(payload.number, "456", "fillInput must write into type=number without InvalidStateError");
+ assert.equal(payload.text, "newtext");
+});
+
+test("fillInput addresses inputs by xpath= and loc=css: (symptom B)", e2eSkip, () => {
+ const script = `
+ const name = 'e2e-fill-selectors';
+ await useOrCreateTaskSpace(name);
+ const html = '<input name="a" type="email" value="">'
+ + '<input name="b" type="text" value="">';
+ await gotoAndWait('data:text/html;charset=utf-8,' + encodeURIComponent(html), { wait: true, timeout: 20 });
+
+ await fillInput('xpath=//input[@name="a"]', '[email protected]');
+ await fillInput('loc=css:input[name="b"]', 'loc-value');
+
+ const a = await elementEval('input[name="a"]', (el) => el.value);
+ const b = await elementEval('input[name="b"]', (el) => el.value);
+
+ await completeTaskSpace(name, { keep: false });
+ cliLog(JSON.stringify({ a, b }));
+ `;
+ const result = runScript(script);
+ const payload = lastJsonLine(result.stderr);
+ assert.equal(payload.a, "[email protected]", "fillInput must accept xpath= selectors");
+ assert.equal(payload.b, "loc-value", "fillInput must accept loc=css: selectors");
+});
diff --git a/package/ego-browser/test/helpers.test.js b/package/ego-browser/test/helpers.test.js
index 9545a82..d877c2c 100644
--- a/package/ego-browser/test/helpers.test.js
+++ b/package/ego-browser/test/helpers.test.js
@@ -401,28 +401,26 @@ test("useOrCreateTaskSpace reuses matching normalized task spaces", async () =>
}
});
-test("fillInput focuses, clears selection, inserts text, and fires framework events", async () => {
- const cdpCalls = [];
- const jsExpressions = [];
+test("fillInput resolves the selector, clears via native value setter, inserts text, and fires framework events", async () => {
+ const calls = [];
await withOverrides({
cdpOverride: async (method, params, sessionId) => {
- cdpCalls.push([method, params, sessionId]);
- if (method === "Runtime.evaluate") {
- jsExpressions.push(params.expression);
- return { result: { value: params.expression.includes("focus") ? true : null } };
- }
+ calls.push([method, params, sessionId]);
+ if (method === "Runtime.evaluate") return { result: { objectId: "obj-css" } };
return {};
}
}, async () => {
await helpers.fillInput("#my-input", "x");
});
- const keyEvents = cdpCalls.filter(([method]) => method === "Input.dispatchKeyEvent").map(([, params]) => params);
- assert.equal(keyEvents.some((event) => event.key === "a"), false);
- assert.ok(keyEvents.some((event) => event.key === "Backspace"));
- assert.ok(cdpCalls.some(([method, params]) => method === "Input.insertText" && params.text === "x"));
- assert.ok(jsExpressions.some((expression) => expression.includes("setSelectionRange")));
- assert.ok(jsExpressions.some((expression) => expression.includes("input") && expression.includes("change")));
+ const callFnOn = calls.filter(([m]) => m === "Runtime.callFunctionOn").map(([, p]) => p);
+ assert.ok(calls.some(([m, p]) => m === "Runtime.evaluate" && /querySelector/.test(p.expression || "")), "must resolve raw CSS via the unified resolver");
+ assert.ok(callFnOn.length > 0 && callFnOn.every((p) => p.objectId === "obj-css"), "callFunctionOn must target the resolved objectId");
+ assert.equal(callFnOn.some((p) => /setSelectionRange/.test(p.functionDeclaration)), false, "must not use setSelectionRange");
+ assert.equal(calls.some(([m, p]) => m === "Input.dispatchKeyEvent" && p.key === "Backspace"), false, "must not clear with Backspace");
+ assert.ok(callFnOn.some((p) => /this\.value\s*=\s*''/.test(p.functionDeclaration)), "must clear via native value setter");
+ assert.ok(calls.some(([m, p]) => m === "Input.insertText" && p.text === "x"), "must insert text via CDP");
+ assert.ok(callFnOn.some((p) => /'input'/.test(p.functionDeclaration) && /'change'/.test(p.functionDeclaration)), "must fire input/change events");
});
test("pressKey sends printable text on keyDown", async () => {
@@ -552,11 +550,13 @@ test("click doubleClick and hover accept viewport coordinate targets", async ()
});
test("waitForElement visible check uses checkVisibility with computed-style fallback", async () => {
- const expressions = [];
+ const calls = [];
await withOverrides({
cdpOverride: async (method, params) => {
- expressions.push(params.expression);
- return { result: { value: true } };
+ calls.push([method, params]);
+ if (method === "Runtime.evaluate") return { result: { objectId: "obj-btn" } };
+ if (method === "Runtime.callFunctionOn") return { result: { value: true } };
+ return {};
},
now: (() => {
let value = 1000;
@@ -566,9 +566,11 @@ test("waitForElement visible check uses checkVisibility with computed-style fall
}, async () => {
assert.equal(await helpers.waitForElement("#btn", { visible: true }), true);
});
- assert.ok(expressions.some((expression) => expression.includes("checkVisibility")));
- assert.ok(expressions.some((expression) => expression.includes("getComputedStyle")));
- assert.equal(expressions.some((expression) => expression.includes("offsetParent")), false);
+ const callFnOn = calls.find(([m]) => m === "Runtime.callFunctionOn");
+ assert.ok(callFnOn, "visibility must be checked via callFunctionOn on the resolved element");
+ assert.match(callFnOn[1].functionDeclaration, /checkVisibility/);
+ assert.match(callFnOn[1].functionDeclaration, /getComputedStyle/);
+ assert.equal(callFnOn[1].functionDeclaration.includes("offsetParent"), false);
});
test("captureScreenshot clips to CSS viewport with scale=1/DPR by default", async () => {
@@ -760,10 +762,11 @@ test("fillInput on @ref resolves to objectId and uses callFunctionOn + Input.ins
const callFnOn = calls.filter(([m]) => m === "Runtime.callFunctionOn");
assert.ok(callFnOn.every(([, p]) => p.objectId === "obj-42"), "callFunctionOn must target the resolved objectId");
assert.ok(callFnOn.some(([, p]) => /this\.focus\(\)/.test(p.functionDeclaration)), "must focus the element");
- assert.ok(callFnOn.some(([, p]) => /setSelectionRange/.test(p.functionDeclaration)), "must select existing value before clearing");
+ assert.equal(callFnOn.some(([, p]) => /setSelectionRange/.test(p.functionDeclaration)), false, "must not use setSelectionRange");
+ assert.ok(callFnOn.some(([, p]) => /this\.value\s*=\s*''/.test(p.functionDeclaration)), "must clear via native value setter");
assert.ok(callFnOn.some(([, p]) => /dispatchEvent\(new Event\('input'/.test(p.functionDeclaration) && /'change'/.test(p.functionDeclaration)), "must fire input/change events");
assert.ok(calls.some(([m, p]) => m === "Input.insertText" && p.text === "hello"), "must insert text via CDP");
- assert.ok(calls.some(([m, p]) => m === "Input.dispatchKeyEvent" && p.key === "Backspace"), "must clear by pressing Backspace");
+ assert.equal(calls.some(([m, p]) => m === "Input.dispatchKeyEvent" && p.key === "Backspace"), false, "must not clear by pressing Backspace");
});
test("fillInput with clearFirst:false on @ref skips the clear+Backspace path", async () => {
@@ -812,10 +815,80 @@ test("dispatchKey on @ref focuses via objectId and dispatches a synthetic Keyboa
assert.deepEqual(callFnOn[0][1].arguments, [
{ value: 13 },
{ value: "Enter" },
+ { value: "Enter" },
{ value: "keypress" }
]);
});
+test("fillInput routes xpath= selectors through the unified resolver", async () => {
+ const calls = [];
+ await withOverrides({
+ cdpOverride: async (method, params) => {
+ calls.push([method, params]);
+ if (method === "Runtime.evaluate") return { result: { objectId: "obj-xp" } };
+ return {};
+ }
+ }, async () => {
+ await helpers.fillInput("xpath=//input[@name='email']", "[email protected]");
+ });
+ assert.ok(calls.some(([m, p]) => m === "Runtime.evaluate" && /document\.evaluate/.test(p.expression || "")), "xpath must resolve via document.evaluate, not querySelector");
+ assert.ok(calls.filter(([m]) => m === "Runtime.callFunctionOn").every(([, p]) => p.objectId === "obj-xp"));
+ assert.ok(calls.some(([m, p]) => m === "Input.insertText" && p.text === "[email protected]"));
+});
+
+test("fillInput routes loc=css: selectors through the unified resolver", async () => {
+ const calls = [];
+ await withOverrides({
+ cdpOverride: async (method, params) => {
+ calls.push([method, params]);
+ if (method === "Runtime.evaluate") {
+ return /querySelectorAll/.test(params.expression) ? { result: { value: 1 } } : { result: { objectId: "obj-loc" } };
+ }
+ return {};
+ }
+ }, async () => {
+ await helpers.fillInput("loc=css:input[name=\"email\"]", "[email protected]");
+ });
+ assert.ok(calls.some(([m, p]) => m === "Runtime.evaluate" && /querySelectorAll/.test(p.expression || "")), "loc=css must check uniqueness via querySelectorAll");
+ assert.ok(calls.some(([m, p]) => m === "Input.insertText" && p.text === "[email protected]"));
+});
+
+test("dispatchKey routes xpath= selectors through the unified resolver", async () => {
+ const calls = [];
+ await withOverrides({
+ cdpOverride: async (method, params) => {
+ calls.push([method, params]);
+ if (method === "Runtime.evaluate") return { result: { objectId: "obj-xp" } };
+ return {};
+ }
+ }, async () => {
+ await helpers.dispatchKey("xpath=//button", "Enter");
+ });
+ assert.ok(calls.some(([m, p]) => m === "Runtime.evaluate" && /document\.evaluate/.test(p.expression || "")));
+ const callFnOn = calls.find(([m]) => m === "Runtime.callFunctionOn");
+ assert.ok(callFnOn, "must dispatch the KeyboardEvent via callFunctionOn on the resolved element");
+ assert.match(callFnOn[1].functionDeclaration, /new KeyboardEvent/);
+});
+
+test("waitForElement routes xpath= selectors through the unified resolver", async () => {
+ const calls = [];
+ await withOverrides({
+ cdpOverride: async (method, params) => {
+ calls.push([method, params]);
+ if (method === "Runtime.evaluate") return { result: { objectId: "obj-xp" } };
+ return {};
+ },
+ now: (() => {
+ let value = 1000;
+ return () => (value += 1);
+ })(),
+ sleep: async () => {}
+ }, async () => {
+ assert.equal(await helpers.waitForElement("xpath=//button"), true);
+ });
+ assert.ok(calls.some(([m, p]) => m === "Runtime.evaluate" && /document\.evaluate/.test(p.expression || "")), "xpath must resolve via document.evaluate, not querySelector");
+});
+
test("waitForElement on @ref polls resolveElementObjectId and returns true when it succeeds", async () => {
const calls = [];
const restoreRef = withRefEntry("12", 12, "button", "Save");
diff --git a/package/ego-browser/test/nav-and-driver.test.js b/package/ego-browser/test/nav-and-driver.test.js
index 15eb3f4..0749ebf 100644
--- a/package/ego-browser/test/nav-and-driver.test.js
+++ b/package/ego-browser/test/nav-and-driver.test.js
@@ -320,32 +320,46 @@ test("waitForNetworkIdle returns false when timeout elapses without idle window"
});
});
-test("uploadFile resolves selector via DOM and sets file inputs", async () => {
+test("uploadFile resolves the selector via the unified resolver and sets file inputs by objectId", async () => {
const calls = [];
await withOverrides({
cdpOverride: async (method, params) => {
calls.push([method, params]);
- if (method === "DOM.getDocument") return { root: { nodeId: 1 } };
- if (method === "DOM.querySelector") return { nodeId: params.selector === "input#file" ? 42 : 0 };
+ if (method === "Runtime.evaluate") return { result: { objectId: "obj-file" } };
return {};
}
}, async () => {
await helpers.uploadFile("input#file", "/tmp/a.png");
await helpers.uploadFile("input#file", ["/tmp/a.png", "/tmp/b.png"]);
});
- assert.deepEqual(calls.at(-1), ["DOM.setFileInputFiles", { files: ["/tmp/a.png", "/tmp/b.png"], nodeId: 42 }]);
+ assert.equal(calls.some(([m]) => m === "DOM.getDocument"), false, "must not walk DOM via DOM.getDocument");
+ assert.deepEqual(calls.at(-1), ["DOM.setFileInputFiles", { files: ["/tmp/a.png", "/tmp/b.png"], objectId: "obj-file" }]);
});
test("uploadFile throws when selector matches no element", async () => {
await withOverrides({
cdpOverride: async (method) => {
- if (method === "DOM.getDocument") return { root: { nodeId: 1 } };
- if (method === "DOM.querySelector") return { nodeId: 0 };
+ if (method === "Runtime.evaluate") return { result: {} };
+ return {};
+ }
+ }, async () => {
+ await assert.rejects(() => helpers.uploadFile("input#missing", "/tmp/a.png"), /Element not found: input#missing/);
+ });
+});
+
+test("uploadFile routes xpath= selectors through the unified resolver", async () => {
+ const calls = [];
+ await withOverrides({
+ cdpOverride: async (method, params) => {
+ calls.push([method, params]);
+ if (method === "Runtime.evaluate") return { result: { objectId: "obj-xp" } };
return {};
}
}, async () => {
- await assert.rejects(() => helpers.uploadFile("input#missing", "/tmp/a.png"), /no element for input#missing/);
+ await helpers.uploadFile("xpath=//input[@type='file']", "/tmp/a.png");
});
+ assert.ok(calls.some(([m, p]) => m === "Runtime.evaluate" && /document\.evaluate/.test(p.expression || "")), "xpath must resolve via document.evaluate, not querySelector");
+ assert.deepEqual(calls.at(-1), ["DOM.setFileInputFiles", { files: ["/tmp/a.png"], objectId: "obj-xp" }]);
});
test("uploadFile on @ref resolves to objectId and calls DOM.setFileInputFiles with objectId", async () => {