How to execute JavaScript on a page with Puppeteer?

To execute JavaScript on a page with Puppeteer, you can use the page.evaluate() function. Here's an example of how to use this function:

  1. First, you need to create a new Puppeteer browser instance:
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); // Your code to execute JavaScript on the page will go here await browser.close(); })();
  1. Then, you can use the page.evaluate() function to execute JavaScript on the page. For example, if you want to change the background color of the page:
await page.evaluate(() => { document.body.style.backgroundColor = 'lightblue'; });
  1. You can also pass arguments to the JavaScript code inside page.evaluate() by providing them as additional arguments to the function:
const color = 'lightblue'; await page.evaluate(color => { document.body.style.backgroundColor = color; }, color);
  1. Finally, make sure to call browser.close() to close the Puppeteer browser instance once you're done executing your JavaScript code.

With these steps, you can execute JavaScript on a page with Puppeteer.