User Agents

Web browsers and everyday web tech, explained

Run Custom Functions in Playwright and Puppeteer

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Running custom functions in a headless browser allows you to execute JavaScript directly within the page's execution context, enabling you to access the DOM, trigger internal site events, or extract data that is only available via the browser's window object. This is achieved using specialized methods like evaluate in Playwright and Puppeteer, which bridge the gap between your Node.js environment and the browser's JavaScript engine.

What You'll Need

  • Node.js installed on your system (LTS version recommended).
  • A project initialized with npm init.
  • Playwright or Puppeteer installed via npm (npm install playwright or npm install puppeteer).
  • A basic understanding of JavaScript and asynchronous programming (async/await).

Step-by-Step

  1. Initialize the Browser Instance: Start by launching the browser in headless mode. In both Playwright and Puppeteer, this involves calling the launch method and creating a new page object. This page object serves as the target for your custom functions.
  2. Navigate to the Target URL: Use the goto method to load the webpage where the custom function needs to run. Ensure you wait for the page to load completely (e.g., using waitUntil: 'networkidle') to avoid running functions on elements that haven't rendered yet.
  3. Define the Execution Context: Decide whether you need to run a simple expression or a complex block of logic. If you only need a value (like document.title), a simple expression suffices. For multi-step logic, you must wrap your code in an anonymous function.
  4. Implement the Evaluate Method: Call page.evaluate(). This method takes a function as an argument, serializes it, sends it to the browser, executes it in the browser's context, and returns the result back to Node.js.
  5. Pass Arguments to the Browser: If your custom function requires data from your Node.js script (such as a username or a specific selector), pass these as second arguments to the evaluate method. Remember that these arguments must be JSON-serializable.
  6. Handle the Return Value: Because evaluate is asynchronous, use the await keyword to capture the result. The return value must also be JSON-serializable; you cannot return a raw DOM element directly to Node.js.
  7. Close the Browser: Once the function has executed and the data is captured, call browser.close() to free up system resources.

Common Mistakes

  • Trying to access Node.js variables inside evaluate: The code inside evaluate runs in the browser, not in Node.js. You cannot use require(), process.env, or variables declared outside the function unless they are passed in as arguments.
  • Returning DOM elements: Attempting to return a document.querySelector('div') will result in an empty object or an error. You must return specific properties of the element, such as element.innerText or element.getAttribute('href').
  • Ignoring Asynchronous Timing: Running a custom function before the page has fully loaded often leads to "cannot read property of null" errors because the target element does not exist yet.
  • Overusing evaluate for simple clicks: Using evaluate(() => document.querySelector('button').click()) is often less reliable than using the built-in page.click('button'), which simulates a real user interaction.

Tips

  • Use Element Handles: In Playwright, you can use elementHandle.evaluate() to run a function on a specific element rather than the whole page, making your code cleaner and more targeted.
  • Leverage browser-side APIs: Use the custom function to trigger window.scrollTo() or to check the window.performance API for loading metrics.
  • Debug with Headful Mode: During development, set headless: false. This allows you to see the browser in action and use the browser's own DevTools console to test your JavaScript before moving it into the evaluate block.
  • Keep functions lean: The more complex the function passed to the browser, the harder it is to debug. Break large tasks into multiple smaller evaluate calls if possible.

Troubleshooting

If your custom function is not executing as expected, first check the console logs. Since the function runs in the browser, console.log() calls inside evaluate will not appear in your terminal by default. In Playwright, use page.on('console', msg => console.log(msg.text())) to pipe browser logs to your terminal.

If you encounter a "Serialization Error," verify that everything you are passing into the function and everything you are returning from it can be converted to JSON. Functions, Promises, and Circular References cannot be passed across the bridge.

If the function returns null or undefined unexpectedly, double-check the selector used inside the browser context. Use the browser's Inspector to confirm the element is not inside an iframe; if it is, you must first switch to the frame context using page.frame() before calling evaluate.

Frequently Asked Questions

Can I run a function that takes a long time to execute?

Yes, but be aware that the browser may timeout. You can increase the timeout settings in your browser configuration or use a more granular approach to avoid blocking the main thread.

Is there a difference between evaluate and evaluateHandle?

Yes. evaluate returns a JSON-serializable value. evaluateHandle returns a reference to an object residing in the browser's memory, allowing you to perform further operations on that object without serializing it.

Can I use custom functions to bypass bot detection?

Custom functions can help simulate human-like behavior, but they are not a complete solution for bypassing sophisticated bot detection systems which look at browser fingerprints and network patterns.

Do I need to use an arrow function inside evaluate?

While not strictly required, arrow functions are the standard convention. The key is that the function must be a standalone block of code that can be stringified and sent to the browser.

Can I execute a script that is stored in an external .js file?

You cannot pass the file directly into evaluate, but you can read the file as a string using fs.readFileSync in Node.js and then use page.addScriptTag({ content: scriptString }) to inject it into the page.