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:
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();
})();
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';
});
page.evaluate()
by providing them as additional arguments to the function:const color = 'lightblue';
await page.evaluate(color => {
document.body.style.backgroundColor = color;
}, color);
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.