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.

add page-context fetch

Aute906bdcbe1d8e
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
index 50a267c..fdb70c0 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/index.mjs
@@ -14,6 +14,7 @@ import {
pageActionsAndPopupCase,
pageBasicOperationsCase,
pageComplexEvaluateCase,
+ pageFetchCase,
pageBudgetCase,
pageLabelCloseCase,
pageLabelCreateCase,
@@ -51,5 +52,6 @@ export const e2eCases = [
{ name: "page adoption and release", body: pageAdoptionCase },
{ name: "page basic operations", body: pageBasicOperationsCase },
{ name: "page complex evaluate", body: pageComplexEvaluateCase },
+ { name: "page fetch", body: pageFetchCase },
{ name: "page actions and popup adoption", body: pageActionsAndPopupCase },
];
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.mjs
index 156bd53..946ddcd 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
@@ -37,6 +37,9 @@ export function pageLabelRestoreCase() {
1,
"a ref printed in the previous process resolves in the restored Page"
);
+ const fetched = await page.fetch("/api/text", { timeout: 2_000 });
+ assertEqual(fetched.status, 200, "a restored Page can make a page-context request");
+ assertEqual(fetched.body, "server text fixture", "the restored Page fetch returns its body");
const before = await listTabs();
await page.goto(baseUrl + "/nav-target?managed=restored");
const after = await listTabs();
@@ -527,3 +530,58 @@ export function pageComplexEvaluateCase() {
await comparison.close();
`;
}
+
+export function pageFetchCase() {
+ return `
+ const task = await taskSpace(taskName);
+ const source = await task.newPage(baseUrl + "/nested/page-fetch/source", {
+ as: "page-fetch-source",
+ });
+ const comparison = await task.newPage(baseUrl + "/secondary?page-fetch=comparison", {
+ as: "page-fetch-comparison",
+ });
+ await source.evaluate(() => {
+ document.cookie = "egoPageFetch=page-cookie; path=/";
+ });
+ await comparison.evaluate("document.title");
+ assertEqual((await currentTab()).targetId, comparison.targetId, "comparison page starts active");
+
+ const response = await source.fetch("../../api/request-info", {
+ method: "POST",
+ headers: {
+ "content-type": "text/plain",
+ "x-page-fetch": "custom-header",
+ },
+ body: "page-body",
+ timeout: 2_000,
+ });
+ assertEqual((await currentTab()).targetId, source.targetId, "page.fetch activates its Page");
+ assertEqual(response.ok, true, "201 is a successful fetch response");
+ assertEqual(response.status, 201, "page.fetch returns the HTTP status");
+ assertEqual(response.statusText, "Created", "page.fetch returns the status text");
+ assertIncludes(response.url, "/api/request-info", "a relative URL resolves in the Page");
+ assertEqual(response.headers["content-type"], "application/json", "response headers are returned");
+ assertEqual(response.headers["x-fixture-response"], "page-fetch", "custom response headers are returned");
+ const request = JSON.parse(response.body);
+ assertEqual(request.method, "POST", "page.fetch forwards the method");
+ assertEqual(request.path, "/api/request-info", "page.fetch reaches the relative endpoint");
+ assertIncludes(request.cookie, "egoPageFetch=page-cookie", "page.fetch uses the Page cookie context");
+ assertEqual(request.origin, baseUrl, "page.fetch sends the Page origin");
+ assertEqual(request.requestHeader, "custom-header", "page.fetch forwards request headers");
+ assertEqual(request.body, "page-body", "page.fetch forwards the request body");
+
+ const errorResponse = await source.fetch("/api/status?code=418", { timeout: 2_000 });
+ assertEqual(errorResponse.ok, false, "non-2xx responses are returned instead of thrown");
+ assertEqual(errorResponse.status, 418, "non-2xx status is preserved");
+ assertEqual(errorResponse.body, "status 418", "non-2xx body is preserved");
+
+ await assertRejects(
+ () => source.fetch("/api/slow?ms=300", { timeout: 20 }),
+ "page.fetch timed out after 20ms",
+ "page.fetch enforces a millisecond timeout"
+ );
+
+ await source.close();
+ await comparison.close();
+ `;
+}
diff --git a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
index 012bc91..b5d70e2 100644
--- a/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/fixture.mjs
@@ -78,6 +78,29 @@ export async function startFixtureServer(taskName) {
});
return;
}
+ if (url.pathname === "/api/request-info") {
+ let body = "";
+ req.on("data", (chunk) => {
+ body += chunk;
+ });
+ req.on("end", () => {
+ res.writeHead(201, {
+ "content-type": "application/json",
+ "x-fixture-response": "page-fetch",
+ });
+ res.end(
+ JSON.stringify({
+ method: req.method,
+ path: url.pathname,
+ cookie: req.headers.cookie || "",
+ origin: req.headers.origin || "",
+ requestHeader: req.headers["x-page-fetch"] || "",
+ body,
+ }),
+ );
+ });
+ return;
+ }
if (url.pathname === "/api/error") {
res.writeHead(500, {
"content-type": "text/plain",
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 5ca21e5..6c17d94 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -69,8 +69,10 @@ function createFixture(rootDir) {
active: tab.targetId === activeTarget,
}));
},
- async cdp(method, params, sessionId) {
- calls.push(["cdp", method, params, sessionId]);
+ async cdp(method, params, sessionId, timeoutMs) {
+ const call = ["cdp", method, params, sessionId];
+ if (timeoutMs !== undefined) call.push(timeoutMs);
+ calls.push(call);
if (method === "Page.navigate") {
const targetId = sessionId.slice("session:".length);
tabs.get(targetId).url = params.url;
@@ -122,6 +124,24 @@ function createFixture(rootDir) {
return { result: { type: "string", value: "complete" } };
}
if (method === "Runtime.callFunctionOn") {
+ if (params.functionDeclaration.includes("window.fetch")) {
+ return {
+ result: {
+ type: "object",
+ value: {
+ ok: false,
+ status: 418,
+ statusText: "I'm a Teapot",
+ url: "https://example.test/api/teapot",
+ headers: {
+ "content-type": "text/plain",
+ "x-fixture": "page-fetch",
+ },
+ body: "short and stout",
+ },
+ },
+ };
+ }
if (params.functionDeclaration.includes("getBoundingClientRect")) {
if (rejectNextClickPoint) {
rejectNextClickPoint = false;
@@ -397,6 +417,77 @@ test("Page evaluate preserves a large nested JSON argument", async () => {
});
});
+test("Page fetch activates its target and returns a structured non-2xx response", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const first = await task.newPage("https://example.test/first");
+ await task.newPage("https://example.test/second");
+
+ const response = await first.fetch("/api/teapot", {
+ method: "POST",
+ headers: { "x-request": "page-fetch" },
+ body: "payload",
+ timeout: 250,
+ });
+
+ assert.deepEqual(response, {
+ ok: false,
+ status: 418,
+ statusText: "I'm a Teapot",
+ url: "https://example.test/api/teapot",
+ headers: {
+ "content-type": "text/plain",
+ "x-fixture": "page-fetch",
+ },
+ body: "short and stout",
+ });
+ assert.equal(fixture.activeTarget(), first.targetId);
+ const fetchCall = fixture.calls.find(
+ ([kind, method, params]) =>
+ kind === "cdp" &&
+ method === "Runtime.callFunctionOn" &&
+ params.functionDeclaration.includes("window.fetch"),
+ );
+ assert.deepEqual(fetchCall[2].arguments, [
+ {
+ value: {
+ url: "/api/teapot",
+ options: {
+ method: "POST",
+ headers: { "x-request": "page-fetch" },
+ body: "payload",
+ },
+ timeoutMs: 250,
+ },
+ },
+ ]);
+ assert.equal(fetchCall[3], "session:target-1");
+ assert.equal(fetchCall[4], 1_250);
+ });
+});
+
+test("Page fetch validates its JSON options and millisecond timeout", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await task.newPage("https://example.test/fetch");
+ const cyclic = {};
+ cyclic.self = cyclic;
+
+ await assert.rejects(
+ () => page.fetch("/api/text", { timeout: 0 }),
+ /positive number of milliseconds/,
+ );
+ await assert.rejects(
+ () => page.fetch("/api/text", { signal: {} }),
+ /does not accept options.signal/,
+ );
+ await assert.rejects(
+ () => page.fetch("/api/text", cyclic),
+ /options must be JSON-serializable/,
+ );
+ });
+});
+
test("Page click stays target-scoped and adopts only tabs opened by the action", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a", { pageBudget: 2 });
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index 24d15e1..7fecdd6 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -53,6 +53,42 @@ type PageGotoOptions = {
timeout?: number;
};
+export type PageFetchOptions = {
+ timeout?: number;
+ method?: string;
+ headers?: Record<string, string>;
+ body?: string;
+ cache?:
+ | "default"
+ | "no-store"
+ | "reload"
+ | "no-cache"
+ | "force-cache"
+ | "only-if-cached";
+ credentials?: "omit" | "same-origin" | "include";
+ integrity?: string;
+ keepalive?: boolean;
+ mode?: "cors" | "no-cors" | "same-origin";
+ redirect?: "follow" | "error" | "manual";
+ referrer?: string;
+ referrerPolicy?: string;
+};
+
+export type PageFetchResponse = {
+ ok: boolean;
+ status: number;
+ statusText: string;
+ url: string;
+ headers: Record<string, string>;
+ body: string;
+};
+
+type PageFetchPayload = {
+ url: string;
+ options: Record<string, unknown>;
+ timeoutMs: number;
+};
+
type PageTarget = {
spaceId: number;
targetId: string;
@@ -502,13 +538,38 @@ export class Page {
}
async evaluate<T = unknown>(
- expression: string | ((argument: any) => T),
+ expression: string | ((argument: any) => T | Promise<T>),
argument?: unknown,
): Promise<T> {
const hasArgument = arguments.length >= 2;
return this.#evaluate(expression, hasArgument, argument, true);
}
+ /**
+ * Run window.fetch inside this Page and return a CDP-serializable response.
+ * Unlike a Node fetch, relative URLs, cookies, CORS, and service workers all
+ * use the addressed document's browser context.
+ */
+ async fetch(
+ url: string,
+ options: PageFetchOptions = {},
+ ): Promise<PageFetchResponse> {
+ assertUrl(url);
+ const payload = pageFetchPayload(url, options);
+ const page = await this.#resolve();
+ return this.#services.gate.withPage(page, async ({ sessionId }) => {
+ await this.#activate(page.targetId);
+ return evaluateInSession<PageFetchResponse>(
+ this.#services,
+ sessionId,
+ fetchInPage,
+ true,
+ payload,
+ payload.timeoutMs + 1_000,
+ );
+ });
+ }
+
async screenshot(
path?: string,
options: CaptureScreenshotOptions = {},
@@ -578,7 +639,7 @@ export class Page {
}
async #evaluate<T>(
- expression: string | ((argument: any) => T),
+ expression: string | ((argument: any) => T | Promise<T>),
hasArgument: boolean,
argument?: unknown,
activate = false,
@@ -680,9 +741,10 @@ export class Page {
async function evaluateInSession<T>(
services: PageModelServices,
sessionId: string,
- expression: string | ((argument: any) => T),
+ expression: string | ((argument: any) => T | Promise<T>),
hasArgument: boolean,
serializedArgument?: unknown,
+ timeoutMs?: number,
): Promise<T> {
if (typeof expression === "string") {
const response = await services.cdp(
@@ -693,6 +755,7 @@ async function evaluateInSession<T>(
awaitPromise: true,
},
sessionId,
+ timeoutMs,
);
return runtimeValue(response, expression) as T;
}
@@ -705,6 +768,7 @@ async function evaluateInSession<T>(
returnByValue: false,
},
sessionId,
+ timeoutMs,
);
const objectId = owner?.result?.objectId;
if (typeof objectId !== "string" || objectId.length === 0) {
@@ -723,6 +787,7 @@ async function evaluateInSession<T>(
awaitPromise: true,
},
sessionId,
+ timeoutMs,
);
return runtimeValue(response, source) as T;
} finally {
@@ -757,25 +822,88 @@ function validateEvaluateInput(
}
function serializeEvaluateArgument(argument: unknown): unknown {
+ return serializeJsonValue(
+ argument,
+ "page.evaluate argument must be JSON-serializable",
+ );
+}
+
+function serializeJsonValue(value: unknown, message: string): unknown {
try {
- const json = JSON.stringify(argument, (_key, value) => {
+ const json = JSON.stringify(value, (_key, item) => {
if (
- typeof value === "undefined" ||
- typeof value === "function" ||
- typeof value === "symbol" ||
- typeof value === "bigint" ||
- (typeof value === "number" && !Number.isFinite(value))
+ typeof item === "undefined" ||
+ typeof item === "function" ||
+ typeof item === "symbol" ||
+ typeof item === "bigint" ||
+ (typeof item === "number" && !Number.isFinite(item))
) {
throw new TypeError("unsupported value");
}
- return value;
+ return item;
});
if (json === undefined) throw new TypeError("unsupported value");
return JSON.parse(json);
} catch (error) {
- throw new TypeError("page.evaluate argument must be JSON-serializable", {
- cause: error,
+ throw new TypeError(message, { cause: error });
+ }
+}
+
+function pageFetchPayload(
+ url: string,
+ options: PageFetchOptions,
+): PageFetchPayload {
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
+ throw new TypeError("page.fetch options must be an object");
+ }
+ if (Object.hasOwn(options, "signal")) {
+ throw new TypeError(
+ "page.fetch does not accept options.signal; use timeout in milliseconds",
+ );
+ }
+ const { timeout = 20_000, ...requestOptions } = options;
+ assertTimeout(timeout);
+ return {
+ url,
+ options: serializeJsonValue(
+ requestOptions,
+ "page.fetch options must be JSON-serializable",
+ ) as Record<string, unknown>,
+ timeoutMs: timeout,
+ };
+}
+
+async function fetchInPage({
+ url,
+ options,
+ timeoutMs,
+}: PageFetchPayload): Promise<PageFetchResponse> {
+ const controller = new AbortController();
+ const timer = window.setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ const response = await window.fetch(url, {
+ ...options,
+ signal: controller.signal,
+ });
+ const headers: Record<string, string> = {};
+ response.headers.forEach((value, key) => {
+ headers[key] = value;
});
+ return {
+ ok: response.ok,
+ status: response.status,
+ statusText: response.statusText,
+ url: response.url,
+ headers,
+ body: await response.text(),
+ };
+ } catch (error) {
+ if (controller.signal.aborted) {
+ throw new Error(`page.fetch timed out after ${timeoutMs}ms`);
+ }
+ throw error;
+ } finally {
+ window.clearTimeout(timer);
}
}