Skip to content

Commit

Permalink
feat: waitForSelector support
Browse files Browse the repository at this point in the history
  • Loading branch information
lino-levan committed Aug 16, 2023
1 parent 9816187 commit 414f92d
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/elementHandle.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 } from "../bindings/celestial.ts";
import { KeyboardTypeOptions } from "./keyboard.ts";
import { Page, ScreenshotOptions } from "./page.ts";
Expand Down Expand Up @@ -228,4 +230,28 @@ export class ElementHandle {
await this.focus();
await this.#page.keyboard.type(text, opts);
}

/**
* Wait for an element matching the given selector to appear in the current element.
*/
async waitForSelector(selector: string) {
// TODO(lino-levan): Make this easier to read, it's a little scuffed
return await deadline<ElementHandle>(
(async () => {
while (true) {
const result = await this.#celestial.DOM.querySelector({
nodeId: this.#id,
selector,
});

if (!result) {
continue;
}

return new ElementHandle(result.nodeId, this.#celestial, this.#page);
}
})(),
this.#page.timeout,
);
}
}
17 changes: 17 additions & 0 deletions src/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,23 @@ export class Page {
);
}

/**
* Wait for the `selector` to appear in page. If at the moment of calling the method the `selector` already exists, the method will return immediately. If the `selector` doesn't appear after the timeout milliseconds of waiting, the function will throw.
*
* @example
* ```ts
* await page.waitForSelector(".class");
* ```
*/
async waitForSelector(selector: string) {
const doc = await retryDeadline(
this.#celestial.DOM.getDocument({ depth: 0 }),
this.timeout,
);
const root = new ElementHandle(doc.root.nodeId, this.#celestial, this);
return root.waitForSelector(selector);
}

/**
* Do not use if there is an alterate way of doing your thing
*
Expand Down
16 changes: 16 additions & 0 deletions tests/wait_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { launch } from "../mod.ts";

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

// Open the webpage
const page = await browser.newPage("http://deno.land");

// Wait for selector
const selected = await page.waitForSelector(".font-bold");
console.log(selected);

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

0 comments on commit 414f92d

Please sign in to comment.