Skip to main content

Waiting for Things

Browserless offers 4 different ways to wait for preconditions to be met on page. These are events, functions, selectors and timeouts

waitForEvent

Waits for an event to happen on the page before cotinue

Example

curl -X POST \
https://production-sfo.browserless.io/screenshot?token=YOUR_API_TOKEN_HERE \
-H 'Cache-Control: no-cache' \
-H 'Content-Type': 'application/json' \
-d '{
"url": "https://example.com/",
"waitForEvent": {
"event": "fullscreenchange",
"timeout": 5000
}
}' \
--output "screenshot.png"

waitForFunction

Waits for the provided function to return before cotinue. The function can be any valid JavaScript or EcmaScript function, and async functions are supported.

Example

JS function

async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const json = await res.json();

document.querySelector("h1").innerText = json.title;
};
curl -X POST \
https://production-sfo.browserless.io/screenshot?token=YOUR_API_TOKEN_HERE \
-H 'Cache-Control: no-cache' \
-H 'Content-Type': 'application/json' \
-d '{
"url": "https://example.com/",
"waitForFunction": {
"fn": "async()=>{let t=await fetch('https://jsonplaceholder.typicode.com/todos/1'),e=await t.json();document.querySelector('h1').innerText=e.title}",
"timeout": 5000
}
}' \
--output "screenshot.png"

waitForSelector

Wait for a 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.

The object can have any of these values:

  • selector: String, required — A valid CSS selector.
  • hidden Boolean, optional — Wait for the selected element to not be found in the DOM or to be hidden, i.e. have display: none or visibility: hidden CSS properties.
  • timeout: Number, optional — Maximum number of milliseconds to wait for the selector before failing.
  • visible: Boolean, optional — Wait for the selected element to be present in DOM and to be visible, i.e. to not have display: none or visibility: hidden CSS properties.

Example

Rest API (Without Stealth)

curl -X POST \
https://production-sfo.browserless.io/screenshot?token=YOUR_API_TOKEN_HERE \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/json' \
-d '{
"url": "https://example.com/",
"waitForSelector": {
"selector": "h1",
"timeout": 5000
}
}'

BQL (Stealth)

If the /pdf API is getting blocked by bot detectors, then we would recommend trying BrowserQL.

mutation PDF {
goto(url: "https://example.com/") {
status
}

waitForSelector(selector: "h1" timeout: 5000) {
selector
}
}
BQL Schemas

For more details on BQL mutations, refer to the BrowserQL Schema reference pages.