How to create a custom function to reuse in Puppeteer scripts?

To create a custom function in Puppeteer, you can define the function in a separate file and then import it into your Puppeteer script. Here's an example of how you can create a custom function to click on an element with a specific selector:

  1. Create a new JavaScript file, for example customFunctions.js, and define your custom function:
const clickElement = async (page, selector) => { try { await page.waitForSelector(selector); await page.click(selector); } catch (error) { console.error(`Error clicking element with selector "${selector}": ${error}`); } } module.exports = { clickElement };
  1. In your Puppeteer script, import the custom function and use it:
const puppeteer = require('puppeteer'); const { clickElement } = require('./customFunctions'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); await clickElement(page, 'button#submit'); await browser.close(); })();

In this example, the custom function clickElement is defined in the customFunctions.js file and then imported into the main Puppeteer script. The function takes two arguments: the Puppeteer page object and the selector of the element to click. This allows you to easily reuse the function in multiple places in your Puppeteer scripts.