Best Practices
There are several ways providing your efficient sessions other than a setup and a launch. Go over some main points concerning properly functioning headless scripts:
Close your session
Facing errors or when finishing the session ensure that browser.close
is launched to start any other sessions. Certainly, long-running sessions are completed by BrowserCloud using a timeout setting. However, finishing your work, you should better just appropriately close it.
const browser = await puppeteer.connect({
browserWSEndpoint: `wss://chrome-v2.browsercloud.io?token=API-TOKEN`,
});
const page = await browser.newPage();
try {
await page.goto('https://www.browsercloud.io/');
await page.screenshot({ path: './browsercloud.png' });
browser.close();
} catch (error) {
console.error({ error }, 'Something happened!');
browser.close();
}
Aviod await's
Note that your command with await
in front of it (or .then
's) goes back and forth from the app to BrowserCloud as most of the puppeteer is async. Use various ways to limit it like using page.evaluate
instead of page.$selector
as in one evaluate
much can be performed compared to multiple $selector
calls.
DON'T DO
const $button = await page.$('.buy-now');
const buttonText = await $button.getProperty('innerText');
const clicked = await $button.click();
DO
const buttonText = await page.evaluate(() => {
const $button = document.querySelector('.buy-now');
const clicked = $button.click();
return $button.innerText;
});