Best practices

Besides setting everything up and running smoothly, there are a few best practices to ensure your sessions perform efficiently. Here are some key tips for maintaining healthy headless scripts.

Close Your Session Properly

When you finish your tasks or encounter errors, make sure to run browser.close() to free up resources for other sessions. While CloudBrowser will terminate long-running sessions based on the timeout setting, it’s always good practice to close sessions neatly once you’re done.

const browser = await puppeteer.connect({
  browserWSEndpoint: `WebSocketDebuggerUrl`,
});

const page = await browser.newPage();

try {
  await page.goto('https://www.cloudbrowser.ai/');
  await page.screenshot({ path: './image.png' });
  browser.close();
} catch (error) {
  console.error({ error }, 'Something went wrong!');
  browser.close();
}

Minimize await Usage

Since most Puppeteer commands are asynchronous, using await (or .then) results in round-trips between your application and CloudBrowser. Although you can’t eliminate this entirely, you should minimize it as much as possible. For example, use page.evaluate instead of multiple page.$selector calls to perform more actions in a single evaluate.

Avoid This:

const $button = await page.$('.buy-now');
const buttonText = await $button.getProperty('innerText');
const clicked = await $button.click();

Do This Instead:

const buttonText = await page.evaluate(() => {
  const $button = document.querySelector('.buy-now');
  const clicked = $button.click();

  return $button.innerText;
});

Last updated