Skip to content

Commit

Permalink
feat: support
Browse files Browse the repository at this point in the history
  • Loading branch information
lino-levan committed Aug 16, 2023
1 parent bb32c75 commit a1bbbc2
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/page.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { deadline } from "https://deno.land/[email protected]/async/deadline.ts";

import { Celestial, Network_Cookie } from "../bindings/celestial.ts";
import { Browser } from "./browser.ts";
import { ElementHandle } from "./elementHandle.ts";
Expand Down Expand Up @@ -35,6 +37,8 @@ export type WaitForNetworkIdleOptions = {
idleConnections?: number;
};

export type EvalFunc<T> = string | (() => T);

export class Page {
#id: string;
#celestial: Celestial;
Expand Down Expand Up @@ -193,7 +197,7 @@ export class Page {
* const innerHTML = await page.evaluate(()=>document.body.innerHTML)
* ```
*/
async evaluate<T>(func: string | (() => T)) {
async evaluate<T>(func: EvalFunc<T>) {
if (typeof func === "function") {
func = `(${func.toString()})()`;
}
Expand Down Expand Up @@ -302,6 +306,25 @@ export class Page {
return convertToUint8Array(data);
}

/**
* Runs a function in the context of the page until it returns a truthy value.
*/
async waitForFunction<T>(func: EvalFunc<T>) {
// TODO(lino-levan): Make this easier to read
await deadline(
(async () => {
while (true) {
const result = await this.evaluate(func);

if (result) {
return result;
}
}
})(),
this.timeout,
);
}

/**
* Waits for the page to navigate to a new URL or to reload. It is useful when you run code that will indirectly cause the page to navigate.
*/
Expand Down
3 changes: 3 additions & 0 deletions tests/__snapshots__/wait_test.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const snapshot = {};

snapshot[`Wait for function 1`] = `undefined`;
19 changes: 19 additions & 0 deletions tests/wait_test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { assertSnapshot } from "https://deno.land/[email protected]/testing/snapshot.ts";
import { launch } from "../mod.ts";

Deno.test("Wait for selector", async () => {
Expand All @@ -14,3 +15,21 @@ Deno.test("Wait for selector", async () => {
// Close browser
await browser.close();
});

Deno.test("Wait for function", async (t) => {
// Launch browser
const browser = await launch();

// Open the webpage
const page = await browser.newPage("https://pyro.deno.dev");

// Wait for function (kind of a stupid case, but whatever, make it better if you see this)
const fetched = await page.waitForFunction(async () => {
const req = await fetch("https://pyro.deno.dev/guides/");
return await req.text();
});
assertSnapshot(t, fetched);

// Close browser
await browser.close();
});

0 comments on commit a1bbbc2

Please sign in to comment.