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.

Support flexible waitForURL matchers

Aute6e562fd9638c
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs
index b88e1fd..993a628 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-load-states.mjs
@@ -368,7 +368,11 @@ export function pageLoadStatesCase() {
);
assert(Boolean(delayedPopup), "background discovery adopts the delayed popup");
const popup = task.page(delayedPopup[0]);
- await popup.waitForURL(/page-load-states=delayed-popup$/, { timeout: 3_000 });
+ await popup.waitForURL("**/secondary?page-load-states=*", { timeout: 3_000 });
+ await popup.waitForURL(
+ (url) => url.searchParams.get("page-load-states") === "delayed-popup",
+ { timeout: 3_000 }
+ );
assertIncludes(
await popup.url(),
"page-load-states=delayed-popup",
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-popup-waiter.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-popup-waiter.mjs
index 39f2f9e..c7a8a99 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-popup-waiter.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-popup-waiter.mjs
@@ -74,7 +74,9 @@ export function pagePopupWaiterCase() {
const startedAt = Date.now();
let waitError;
try {
- await source.waitForURL(/popup-waiter=wrong-page$/, { timeout: 15_000 });
+ await source.waitForURL("**/secondary?popup-waiter=wrong-page", {
+ timeout: 15_000,
+ });
} catch (error) {
waitError = error;
}
diff --git a/package/ego-browser/src/driver/page-waits.test.mjs b/package/ego-browser/src/driver/page-waits.test.mjs
index 5727292..405dfde 100644
--- a/package/ego-browser/src/driver/page-waits.test.mjs
+++ b/package/ego-browser/src/driver/page-waits.test.mjs
@@ -48,6 +48,73 @@ test("waitForURLInPage recovers from a transient execution-context change", asyn
);
});
+test("waitForURLInPage supports Playwright-style URL globs", async () => {
+ let now = 0;
+ let attempt = 0;
+ const services = {
+ async cdp() {
+ attempt += 1;
+ return {
+ result: {
+ value:
+ attempt === 1
+ ? "https://example.test/releases/draft/nested/item?channel=canary"
+ : "https://example.test/releases/ready/item?channel=stable",
+ },
+ };
+ },
+ now: () => now,
+ async sleep(ms) {
+ now += ms;
+ },
+ };
+
+ await waitForURLInPage(
+ services,
+ "session:page",
+ "**/releases/{draft,ready}/*?channel=*",
+ { timeout: 500 },
+ );
+
+ assert.equal(attempt, 2, "a single star must not cross a path separator");
+});
+
+test("waitForURLInPage passes a URL object to a synchronous predicate", async () => {
+ let now = 0;
+ let attempt = 0;
+ const seen = [];
+ const services = {
+ async cdp() {
+ attempt += 1;
+ return {
+ result: {
+ value: `https://example.test/jobs?id=${attempt === 1 ? 41 : 42}`,
+ },
+ };
+ },
+ now: () => now,
+ async sleep(ms) {
+ now += ms;
+ },
+ };
+
+ await waitForURLInPage(
+ services,
+ "session:page",
+ (url) => {
+ assert(url instanceof URL);
+ seen.push(url.href);
+ return url.searchParams.get("id") === "42";
+ },
+ { timeout: 500 },
+ );
+
+ assert.deepEqual(seen, [
+ "https://example.test/jobs?id=41",
+ "https://example.test/jobs?id=42",
+ ]);
+});
+
test("document load waits do not sleep past the budget after a slow probe", async () => {
let now = 0;
let calls = 0;
diff --git a/package/ego-browser/src/driver/page-waits.ts b/package/ego-browser/src/driver/page-waits.ts
index dcee285..81e4b7d 100644
--- a/package/ego-browser/src/driver/page-waits.ts
+++ b/package/ego-browser/src/driver/page-waits.ts
@@ -51,8 +51,13 @@ export type PageWaitForURLOptions = {
timeout?: number;
};
+export type PageURLMatcher = string | RegExp | ((url: URL) => boolean);
+
export type PageWaitForURLHooks = {
- interrupt?: (lastUrl: string) => Error | undefined;
+ interrupt?: (
+ lastUrl: string,
+ matches: (url: string) => boolean,
+ ) => Error | undefined;
};
export class PageNavigationTimeoutError extends Error {
@@ -157,29 +162,16 @@ export async function waitForSelectorInPage(
);
}
-/** Wait until one Page reaches an exact URL or matches a regular expression. */
+/** Wait until one Page URL matches an exact string, glob, RegExp, or predicate. */
export async function waitForURLInPage(
services: PageWaitServices,
sessionId: string,
- expected: string | RegExp,
+ expected: PageURLMatcher,
options: PageWaitForURLOptions = {},
hooks: PageWaitForURLHooks = {},
): Promise<void> {
- if (
- !(
- (typeof expected === "string" && expected.length > 0) ||
- expected instanceof RegExp
- )
- ) {
- throw new TypeError(
- "page.waitForURL expected URL must be a non-empty string or RegExp",
- );
- }
+ const matcher = compilePageURLMatcher(expected);
const timeoutMs = options.timeout ?? 10_000;
- const pattern =
- expected instanceof RegExp
- ? new RegExp(expected.source, expected.flags)
- : undefined;
const deadline = services.now() + timeoutMs;
let lastUrl = "";
while (services.now() <= deadline) {
@@ -201,28 +193,160 @@ export async function waitForURLInPage(
}
if (typeof response?.result?.value === "string") {
lastUrl = response.result.value;
- if (typeof expected === "string") {
- if (lastUrl === expected) return;
- } else {
- pattern!.lastIndex = 0;
- if (pattern!.test(lastUrl)) return;
- }
+ if (matcher.matches(lastUrl)) return;
}
- const interruption = hooks.interrupt?.(lastUrl);
+ const interruption = hooks.interrupt?.(lastUrl, matcher.matches);
if (interruption) throw interruption;
const waitMs = deadline - services.now();
if (waitMs <= 0) break;
await services.sleep(Math.min(100, waitMs));
}
- const expectation =
- typeof expected === "string"
- ? JSON.stringify(expected)
- : expected.toString();
throw new Error(
- `page.waitForURL timed out after ${timeoutMs}ms: expected ${expectation}; last URL was ${JSON.stringify(lastUrl)}`,
+ `page.waitForURL timed out after ${timeoutMs}ms: expected ${matcher.description}; last URL was ${JSON.stringify(lastUrl)}`,
);
}
+function compilePageURLMatcher(expected: PageURLMatcher): {
+ matches(url: string): boolean;
+ description: string;
+} {
+ if (typeof expected === "string") {
+ if (expected.length === 0) {
+ throw invalidPageURLMatcherError();
+ }
+ const pattern = urlGlobToRegExp(expected);
+ return {
+ matches: (url) => pattern.test(url),
+ description: JSON.stringify(expected),
+ };
+ }
+
+ if (expected instanceof RegExp) {
+ const pattern = new RegExp(expected.source, expected.flags);
+ return {
+ matches(url) {
+ pattern.lastIndex = 0;
+ return pattern.test(url);
+ },
+ description: pattern.toString(),
+ };
+ }
+
+ if (typeof expected === "function") {
+ return {
+ matches(url) {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return false;
+ }
+ const result = expected(parsed);
+ if (typeof result !== "boolean") {
+ throw new TypeError(
+ "page.waitForURL predicate must return a boolean synchronously",
+ );
+ }
+ return result;
+ },
+ description: "a URL predicate",
+ };
+ }
+
+ throw invalidPageURLMatcherError();
+}
+
+function invalidPageURLMatcherError(): TypeError {
+ return new TypeError(
+ "page.waitForURL expected URL must be a non-empty string, RegExp, or function",
+ );
+}
+
+const URL_REGEX_SPECIAL_CHARS = new Set([
+ "$",
+ "^",
+ "+",
+ ".",
+ "*",
+ "(",
+ ")",
+ "|",
+ "\\",
+ "?",
+ "{",
+ "}",
+ "[",
+ "]",
+]);
+
+/** Compile the URL-glob subset used by Playwright string matchers. */
+function urlGlobToRegExp(glob: string): RegExp {
+ const tokens = ["^"];
+ let inGroup = false;
+
+ for (let index = 0; index < glob.length; index += 1) {
+ const char = glob[index];
+ if (char === "\\" && index + 1 < glob.length) {
+ const escaped = glob[(index += 1)];
+ tokens.push(
+ URL_REGEX_SPECIAL_CHARS.has(escaped) ? `\\${escaped}` : escaped,
+ );
+ continue;
+ }
+
+ if (char === "*") {
+ const charBefore = glob[index - 1];
+ let starCount = 1;
+ while (glob[index + 1] === "*") {
+ starCount += 1;
+ index += 1;
+ }
+ if (starCount === 1) {
+ tokens.push("[^/]*");
+ continue;
+ }
+
+ const charAfter = glob[index + 1];
+ if (charAfter === "/") {
+ tokens.push(charBefore === "/" ? "(?:(?:.+)/)?" : "(?:.*/)");
+ index += 1;
+ } else {
+ tokens.push(".*");
+ }
+ continue;
+ }
+
+ if (char === "{") {
+ if (inGroup) {
+ throw invalidURLGlobError(glob, "nested '{' is not supported");
+ }
+ inGroup = true;
+ tokens.push("(");
+ continue;
+ }
+ if (char === "}") {
+ if (!inGroup) throw invalidURLGlobError(glob, "unmatched '}'");
+ inGroup = false;
+ tokens.push(")");
+ continue;
+ }
+ if (char === "," && inGroup) {
+ tokens.push("|");
+ continue;
+ }
+
+ tokens.push(URL_REGEX_SPECIAL_CHARS.has(char) ? `\\${char}` : char);
+ }
+
+ if (inGroup) throw invalidURLGlobError(glob, "unmatched '{'");
+ tokens.push("$");
+ return new RegExp(tokens.join(""));
+}
+
+function invalidURLGlobError(glob: string, reason: string): TypeError {
+ return new TypeError(`Invalid URL glob ${JSON.stringify(glob)}: ${reason}`);
+}
+
/** Navigate one Page and wait for the selected state of this navigation. */
export async function navigateInPage(
services: PageWaitServices,
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 3ad73f5..d61415b 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -4180,6 +4180,12 @@ test("Page waitForURL follows a popup from about:blank without activating it", a
await popup.waitForURL(expectedUrl, { timeout: 500 });
await popup.waitForURL(/delayed-popup$/, { timeout: 1 });
+ await popup.waitForURL("**/delayed-popup", { timeout: 1 });
+ await popup.waitForURL(
+ (url) =>
+ url.hostname === "example.test" && url.pathname === "/delayed-popup",
+ { timeout: 1 },
+ );
assert.equal(await popup.url(), expectedUrl);
assert.equal(
@@ -4262,7 +4268,7 @@ test("Page.waitForURL immediately reports a matching popup opened by this Page",
await source.click("#open-popup");
await assert.rejects(
- source.waitForURL(/\/drive\/home/, { timeout: 15_000 }),
+ source.waitForURL("**/drive/home", { timeout: 15_000 }),
(error) => {
assert.equal(error.code, "EGO_URL_OPENED_IN_POPUP");
assert.match(error.message, /p1 did not navigate/);
@@ -4301,11 +4307,19 @@ test("Page waitForURL validates its matcher and reports the last URL", async ()
);
await assert.rejects(
() => page.waitForURL("", { timeout: 10 }),
- /non-empty string or RegExp/,
+ /non-empty string, RegExp, or function/,
);
await assert.rejects(
() => page.waitForURL(42, { timeout: 10 }),
- /non-empty string or RegExp/,
+ /non-empty string, RegExp, or function/,
+ );
+ await assert.rejects(
+ () => page.waitForURL(async () => true, { timeout: 10 }),
+ /predicate must return a boolean synchronously/,
+ );
+ await assert.rejects(
+ () => page.waitForURL("**/{ready", { timeout: 10 }),
+ /Invalid URL glob.*unmatched '\{'/,
);
await assert.rejects(
() => page.waitForURL(/blank/, { timeout: 0 }),
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index 9907ba1..837abd0 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -70,6 +70,7 @@ import {
waitForSelectorInPage,
waitForURLInPage,
type PageGotoWaitUntil,
+ type PageURLMatcher,
type PageWaitForLoadStateOptions,
type PageWaitForSelectorOptions,
type PageWaitForURLOptions,
@@ -1505,15 +1506,15 @@ class Page {
}
async waitForURL(
- expected: string | RegExp,
+ expected: PageURLMatcher,
options: PageWaitForURLOptions = {},
): Promise<void> {
validatePublicApiOptions("Page.waitForURL", options);
const page = await this.#resolve();
return this.#services.gate.withPage(page, ({ sessionId }) =>
waitForURLInPage(this.#services, sessionId, expected, options, {
- interrupt: (lastUrl) =>
- matchingPopupWaitError(this.spaceId, this.label, lastUrl, expected),
+ interrupt: (lastUrl, matches) =>
+ matchingPopupWaitError(this.spaceId, this.label, lastUrl, matches),
}),
);
}
@@ -3064,14 +3065,14 @@ function matchingPopupWaitError(
spaceId: number,
openerLabel: string,
lastUrl: string,
- expected: string | RegExp,
+ matches: (url: string) => boolean,
): (Error & { code: string }) | undefined {
const popup = peekUnhandledPageNotices().find(
(notice) =>
notice.spaceId === spaceId &&
notice.openerLabel === openerLabel &&
typeof notice.url === "string" &&
- urlMatches(notice.url, expected),
+ matches(notice.url),
);
if (!popup) return undefined;
@@ -3085,13 +3086,6 @@ function matchingPopupWaitError(
return error;
}
-function urlMatches(url: string, expected: string | RegExp): boolean {
- if (typeof expected === "string") return url === expected;
- const pattern = new RegExp(expected.source, expected.flags);
- pattern.lastIndex = 0;
- return pattern.test(url);
-}
-
function assertCdpCall(
apiName: "Page.cdp" | "TaskSpace.cdp",
method: string,
diff --git a/package/ego-browser/src/public-api-schema.test.mjs b/package/ego-browser/src/public-api-schema.test.mjs
index 722b4b5..2591bcb 100644
--- a/package/ego-browser/src/public-api-schema.test.mjs
+++ b/package/ego-browser/src/public-api-schema.test.mjs
@@ -153,6 +153,10 @@ test("the generated reference contains signatures and option descriptions", () =
markdown,
/`await page\.waitForEvent\("popup", \{ timeout\? \}\)`/,
);
+ assert.match(
+ markdown,
+ /`await page\.waitForURL\(urlMatcher, \{ timeout\? \}\)`.*Playwright-style glob.*predicate receiving a URL object/,
+ );
assert.match(
markdown,
/`await page\.waitForFunction\(fnOrString, argument\?, \{ timeout\?, polling\? \}\)`/,
diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.ts
index 481e6c9..94153a9 100644
--- a/package/ego-browser/src/public-api-schema.ts
+++ b/package/ego-browser/src/public-api-schema.ts
@@ -273,8 +273,9 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
},
{
name: "Page.waitForURL",
- signature: "await page.waitForURL(urlOrRegExp, { timeout? })",
- summary: "Wait for an exact URL or regular-expression match.",
+ signature: "await page.waitForURL(urlMatcher, { timeout? })",
+ summary:
+ "Wait for an exact URL, Playwright-style glob, RegExp, or synchronous predicate receiving a URL object.",
options: { timeout },
},
{
diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.md
index 82951e1..b0ce58a 100644
--- a/skills/ego-browser/references/api.md
+++ b/skills/ego-browser/references/api.md
@@ -52,7 +52,7 @@ Selectors accept refs, Ego locators, XPath, and raw CSS. A small compatibility s
| `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?, scale?, raw? })` | `path` — Output path; missing parent directories are created.<br>`fullPage` — Capture the full scrollable page.<br>`clip` — CSS-pixel clipping rectangle.<br>`scale` (css) — Output scale mode; css uses CSS-pixel sizing and is the default.<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.waitForURL(urlMatcher, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for an exact URL, Playwright-style glob, RegExp, or synchronous predicate receiving a URL object. |
| `await page.waitForEvent("popup", { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for this Page's next popup; call before the triggering action. |
| `await page.waitForTimeout(timeout)` | — | Wait a fixed number of milliseconds without activating this Page. |
| `await page.title()` | — | Read this Page's current title. |