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): add page function waits
Aute4f0b0540bb97
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 6a527c2..45fafe2 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@@ -276,6 +276,16 @@ export function pageBasicOperationsCase() {document.body.append(ready);}, 75);});+ assertEqual(+ await first.waitForFunction(+ ({ selector, expected }) =>+ document.querySelector(selector)?.textContent === expected,+ { selector: "#page-wait-ready", expected: "Ready" },+ { timeout: 2_000, polling: 25 }+ ),+ true,+ "page.waitForFunction polls the addressed Page with one JSON argument"+ );assertEqual(await first.waitForSelector("#page-wait-ready", {timeout: 2_000,diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjsindex a0e1028..9d11ac4 100644--- a/package/ego-browser/src/page-model.test.mjs+++ b/package/ego-browser/src/page-model.test.mjs@@ -53,6 +53,7 @@ function createFixture(rootDir) {let domContentLoaded = true;let timeoutNextLifecycleEvaluate = false;let timeoutNextUrlEvaluate = false;+ let waitFunctionResults = [];let nowMs = 1_000;const pageEvents = new Map();const networkSessions = new Set();@@ -120,6 +121,14 @@ function createFixture(rootDir) {if (method === "Runtime.evaluate") {const targetId = targetForSession(sessionId);const tab = tabs.get(targetId);+ if (params.expression.includes("__egoWaitForFunction")) {+ return {+ result: {+ type: "boolean",+ value: waitFunctionResults.shift() ?? false,+ },+ };+ }if (timeoutNextLifecycleEvaluate &&(params.expression === "document.readyState" ||@@ -219,6 +228,21 @@ function createFixture(rootDir) {return { result: { type: "string", value: "complete" } };}if (method === "Runtime.callFunctionOn") {+ if (params.functionDeclaration.includes("missingClosureForE2E")) {+ return {+ result: {+ type: "object",+ subtype: "error",+ description:+ "ReferenceError: missingClosureForE2E is not defined",+ },+ exceptionDetails: {+ text: "Uncaught",+ lineNumber: 0,+ columnNumber: 0,+ },+ };+ }if (params.functionDeclaration.includes("focusElementForAction")) {return {result: { type: "object", value: focusResult },@@ -607,6 +631,9 @@ function createFixture(rootDir) {timeoutNextUrlEvaluation() {timeoutNextUrlEvaluate = true;},+ setWaitFunctionResults(results) {+ waitFunctionResults = [...results];+ },setSession(targetId, sessionId) {sessionOverrides.set(targetId, sessionId);},@@ -838,6 +865,100 @@ test("Page.waitForTimeout validates and waits in milliseconds without activating});});+test("Page.waitForFunction polls one Page with one JSON argument", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const first = await task.openPage("https://example.test/first");+ const second = await task.openPage("https://example.test/second");+ fixture.setWaitFunctionResults([false, false, true]);+ fixture.calls.length = 0;++ assert.equal(+ await first.waitForFunction(+ ({ selector }) => Boolean(document.querySelector(selector)),+ { selector: "#ready" },+ { timeout: 250, polling: 25 },+ ),+ true,+ );++ const probes = fixture.calls.filter(+ ([kind, method, params, sessionId]) =>+ kind === "cdp" &&+ method === "Runtime.evaluate" &&+ params.expression.includes("__egoWaitForFunction") &&+ sessionId === "session:target-1",+ );+ assert.equal(probes.length, 3);+ assert.match(probes[0][2].expression, /"selector":"#ready"/);+ assert(+ fixture.calls.some(+ ([kind, method, params]) =>+ kind === "cdp" &&+ method === "Target.activateTarget" &&+ params.targetId === first.targetId,+ ),+ "waitForFunction activates the addressed Page",+ );+ assert.equal(second.targetId, "target-2");+ });+});++test("Page.waitForFunction validates input and reports its timeout", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await task.openPage("https://example.test/first");++ await assert.rejects(+ () =>+ page.waitForFunction(() => false, undefined, {+ timeout: 60,+ polling: 25,+ }),+ /page\.waitForFunction timed out after 60ms/,+ );+ await assert.rejects(+ () => page.waitForFunction(42),+ /page\.waitForFunction expects a function or string expression/,+ );+ await assert.rejects(+ () => page.waitForFunction("document.readyState", { ignored: true }),+ /string expression does not accept an argument/,+ );+ await assert.rejects(+ () => page.waitForFunction(() => true, undefined, { timeout: 0 }),+ /timeout must be a positive number of milliseconds/,+ );+ await assert.rejects(+ () => page.waitForFunction(() => true, undefined, { polling: 0 }),+ /polling must be a positive number of milliseconds/,+ );+ });+});++test("Page.evaluate explains that its callback cannot capture Node variables", async () => {+ await withFixture(async (fixture) => {+ const task = taskForRound(fixture, "round-a");+ const page = await task.openPage("https://example.test/first");++ await assert.rejects(+ () => page.evaluate(() => missingClosureForE2E),+ (error) => {+ assert.match(+ error.message,+ /ReferenceError: missingClosureForE2E is not defined/,+ );+ assert.match(+ error.message,+ /page\.evaluate\(\) callbacks run inside the Page and cannot access variables from the Node\.js script/,+ );+ assert.match(error.message, /pass JSON data as the second argument/);+ return true;+ },+ );+ });+});+test("v2 methods reject option fields that are absent from the public schema", async () => {await withFixture(async (fixture) => {const task = taskForRound(fixture, "round-a");diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.tsindex b7d7093..0c77a99 100644--- a/package/ego-browser/src/page-model.ts+++ b/package/ego-browser/src/page-model.ts@@ -154,6 +154,11 @@ type PageWaitForEventOptions = {timeout?: number;};+type PageWaitForFunctionOptions = {+ timeout?: number;+ polling?: number;+};+export type PageFetchOptions = {timeout?: number;method?: string;@@ -1403,6 +1408,72 @@ class Page {return this.#evaluate(expression, hasArgument, argument, true);}+ /** Wait until a Page expression returns a truthy value. */+ async waitForFunction(+ expression: string | ((argument: any) => unknown | Promise<unknown>),+ argument?: unknown,+ options: PageWaitForFunctionOptions = {},+ ): Promise<true> {+ validatePublicApiOptions("Page.waitForFunction", options);+ // Passing `undefined` is how callers omit the optional argument while+ // supplying the third options parameter, matching Playwright's shape.+ const hasArgument = arguments.length >= 2 && argument !== undefined;+ const serializedArgument = validateEvaluateInput(+ "page.waitForFunction",+ expression,+ hasArgument,+ argument,+ );+ const timeoutMs = options.timeout ?? 10_000;+ const pollingMs = options.polling ?? 100;+ const source = waitForFunctionExpression(+ expression,+ hasArgument,+ serializedArgument,+ );+ const page = await this.#resolve();++ return this.#services.gate.withPage(page, async ({ sessionId }) => {+ await this.#activate(page.targetId);+ const deadline = this.#services.now() + timeoutMs;+ try {+ while (this.#services.now() <= deadline) {+ const remaining = Math.max(1, deadline - this.#services.now());+ try {+ const response = await this.#services.cdp(+ "Runtime.evaluate",+ {+ expression: source,+ returnByValue: true,+ awaitPromise: true,+ },+ sessionId,+ Math.min(1_000, remaining),+ );+ if (runtimeValue(response, source) === true) return true as const;+ } catch (error) {+ if (!isRetryablePageEvaluationError(error)) {+ throw enrichPageCallbackReferenceError(+ error,+ "page.waitForFunction",+ );+ }+ if (this.#services.now() >= deadline) break;+ }++ const waitMs = deadline - this.#services.now();+ if (waitMs <= 0) break;+ await this.#services.sleep(Math.min(pollingMs, waitMs));+ }+ } finally {+ // The predicate may mutate the DOM, so snapshot refs are no longer+ // guaranteed to identify the same elements.+ this.#services.pageRefs.clear(page.targetId);+ }+ throw new Error(`page.waitForFunction timed out after ${timeoutMs}ms`);+ });+ }+/*** Run window.fetch inside this Page and return a CDP-serializable response.* Unlike a Node fetch, relative URLs, cookies, CORS, and service workers all@@ -1842,6 +1913,7 @@ class Page {activate = false,): Promise<T> {const serializedArgument = validateEvaluateInput(+ "page.evaluate",expression,hasArgument,argument,@@ -1850,13 +1922,20 @@ class Page {return this.#services.gate.withPage(page, async ({ sessionId }) => {if (activate) await this.#activate(page.targetId);try {- return await evaluateInSession<T>(- this.#services,- sessionId,- expression,- hasArgument,- serializedArgument,- );+ try {+ return await evaluateInSession<T>(+ this.#services,+ sessionId,+ expression,+ hasArgument,+ serializedArgument,+ );+ } catch (error) {+ if (typeof expression === "function") {+ throw enrichPageCallbackReferenceError(error, "page.evaluate");+ }+ throw error;+ }} finally {if (activate) this.#services.pageRefs.clear(page.targetId);}@@ -2180,36 +2259,79 @@ async function evaluateInSession<T>(}function validateEvaluateInput(+ apiName: string,expression: unknown,hasArgument: boolean,argument: unknown,): unknown {if (typeof expression !== "string" && typeof expression !== "function") {- throw new TypeError(- "page.evaluate expects a function or string expression",- );+ throw new TypeError(`${apiName} expects a function or string expression`);}if (typeof expression === "string") {if (expression.length === 0) {- throw new TypeError("page.evaluate expression must not be empty");+ throw new TypeError(`${apiName} expression must not be empty`);}if (hasArgument) {throw new TypeError(- "page.evaluate string expression does not accept an argument",+ `${apiName} string expression does not accept an argument`,);}return undefined;}- return hasArgument ? serializeEvaluateArgument(argument) : undefined;+ return hasArgument ? serializeEvaluateArgument(apiName, argument) : undefined;}-function serializeEvaluateArgument(argument: unknown): unknown {+function serializeEvaluateArgument(+ apiName: string,+ argument: unknown,+): unknown {return serializeJsonValue(argument,- "page.evaluate argument must be JSON-serializable",+ `${apiName} argument must be JSON-serializable`,+ );+}++function waitForFunctionExpression(+ expression: string | ((argument: any) => unknown | Promise<unknown>),+ hasArgument: boolean,+ serializedArgument: unknown,+): string {+ if (typeof expression === "string") {+ return `(async function __egoWaitForFunction() { return Boolean(await (${expression})); })()`;+ }+ const source = expression.toString();+ const argument = hasArgument ? JSON.stringify(serializedArgument) : "";+ return `(async function __egoWaitForFunction() { return Boolean(await (${source})(${argument})); })()`;+}++function isRetryablePageEvaluationError(error: unknown): boolean {+ if (!(error instanceof Error)) return false;+ return (+ error.message.includes("CDP request timed out: Runtime.evaluate") ||+ error.message.includes("Execution context was destroyed") ||+ error.message.includes("Cannot find context with specified id") ||+ error.message.includes("Inspected target navigated"));}+function enrichPageCallbackReferenceError(+ error: unknown,+ apiName: string,+): unknown {+ if (+ !(error instanceof Error) ||+ !/\bReferenceError: .* is not defined/.test(error.message) ||+ error.message.includes("cannot access variables from the Node.js script")+ ) {+ return error;+ }+ error.message +=+ `\n${apiName}() callbacks run inside the Page and cannot access variables ` ++ "from the Node.js script. Define the value inside the callback or pass " ++ "JSON data as the second argument.";+ return error;+}+function serializeJsonValue(value: unknown, message: string): unknown {try {const json = JSON.stringify(value, (_key, item) => {diff --git a/package/ego-browser/src/public-api-schema.test.mjs b/package/ego-browser/src/public-api-schema.test.mjsindex e3979be..ce56c6b 100644--- a/package/ego-browser/src/public-api-schema.test.mjs+++ b/package/ego-browser/src/public-api-schema.test.mjs@@ -25,6 +25,7 @@ test("the public API schema contains the v2 entry points and object methods", ()"Page.waitForEvent","Page.waitForURL","Page.waitForTimeout",+ "Page.waitForFunction","Page.focus","Page.press","Page.keyboard.press",@@ -72,6 +73,10 @@ test("schema-driven option validation rejects unknown and invalid fields", () =>() => validatePublicApiOptions("Page.goto", { waitUntil: "interactive" }),/waitUntil must be one of commit, domcontentloaded, load, networkidle/,);+ assert.throws(+ () => validatePublicApiOptions("Page.waitForFunction", { polling: 0 }),+ /polling must be a positive number of milliseconds/,+ );assert.throws(() => validatePublicApiOptions("Page.click", { button: "primary" }),/button must be one of left, middle, right/,@@ -95,6 +100,10 @@ test("the generated reference contains signatures and option descriptions", () =markdown,/`await page\.waitForEvent\("popup", \{ timeout\? \}\)`/,);+ assert.match(+ markdown,+ /`await page\.waitForFunction\(fnOrString, argument\?, \{ timeout\?, polling\? \}\)`/,+ );assert.match(markdown,/const popupPromise = page\.waitForEvent\("popup"\); await page\.click\(selector\)/,diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.tsindex a56f8d8..a269799 100644--- a/package/ego-browser/src/public-api-schema.ts+++ b/package/ego-browser/src/public-api-schema.ts@@ -280,7 +280,21 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [{name: "Page.evaluate",signature: "await page.evaluate(fnOrString, argument?)",- summary: "Run JavaScript in this Page with JSON-serializable data.",+ summary:+ "Run JavaScript in this Page; callbacks receive JSON data but cannot capture Node.js variables.",+ },+ {+ name: "Page.waitForFunction",+ signature:+ "await page.waitForFunction(fnOrString, argument?, { timeout?, polling? })",+ summary: "Wait until a Page function or expression returns a truthy value.",+ options: {+ timeout,+ polling: option(+ "positiveMilliseconds",+ "Polling interval in milliseconds; defaults to 100.",+ ),+ },},{name: "Page.fetch",diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.mdindex 40af8dc..433c64f 100644--- a/skills/ego-browser/SKILL.md+++ b/skills/ego-browser/SKILL.md@@ -54,7 +54,7 @@ use `help("profiles")` for the exact workflow.Common TaskSpace API:- State: `spaceId`, `name`, `ownership`, `page(label)`, `userPage()`-- Pages: `pages()`, `tabs()`, `openPage(url, { as?, timeout? })`,+- Pages: `await task.pages()`, `await task.tabs()`, `openPage(url, { as?, timeout? })`,`adopt(page, { as? })`, `release(label)`- Control: `waitForControl(options)`, `handOff()`, `finish()`, `close()`- Advanced: `cdp(method, params, options)`@@ -63,7 +63,7 @@ Pages receive permanent labels such as `p1`, `p2`, and `p3`. Prefer these labelsto custom `{ as }` values. A space manages at most eight Pages; close a temporaryPage or reuse an existing one when the limit is reached.-`task.pages()` returns managed Pages. `task.tabs()` returns every tab in the+`await task.pages()` returns managed Pages. `await task.tabs()` returns every tab in thespace as `{ label?, page, targetId, title, url, active, openedBy }`. A tabwithout a label is unmanaged; adopt it before operating:@@ -87,7 +87,7 @@ not the full Playwright API and has no Locator API. Common Page API:- State and observation: `label`, `spaceId`, `openedBy`, `targetId`, `url()`,`title()`, `info()`, `events()`, `snapshot()`, `screenshot()`- Navigation and waits: `goto()`, `waitForURL()`, `waitForSelector()`,- `waitForLoadState()`, `waitForTimeout()`+ `waitForLoadState()`, `waitForFunction()`, `waitForTimeout()`- Elements: `click()`, `dblclick()`, `hover()`, `dragAndDrop()`, `fill()`,`focus()`, `press()`, `scrollBy()`, `setInputFiles()`,`waitForFileChooser()`, `close()`@@ -97,6 +97,10 @@ not the full Playwright API and has no Locator API. Common Page API:- Page code and protocols: `evaluate(fnOrString, argument)`,`fetch(url, options)`, `cdp(method, params, options)`+`page.evaluate()` callbacks run inside the Page, so they cannot read variables+from the surrounding Node.js script. Define browser-side helpers inside the+callback or pass one JSON-serializable value as its second argument.+### Semantic pages: snapshot and selectorsFor an ordinary DOM page, use an observe → act → observe loop.diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.mdindex 4928fe9..d2b9024 100644--- a/skills/ego-browser/references/api.md+++ b/skills/ego-browser/references/api.md@@ -55,7 +55,8 @@ For an explicit popup wait, arm it before the action: `const popupPromise = page| `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.evaluate(fnOrString, argument?)` | — | Run JavaScript in this Page; callbacks receive JSON data but cannot capture Node.js variables. |+| `await page.waitForFunction(fnOrString, argument?, { timeout?, polling? })` | `timeout` — Maximum duration in milliseconds.<br>`polling` — Polling interval in milliseconds; defaults to 100. | Wait until a Page function or expression returns a truthy value. || `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. |