Execute JavaScript function on the page context of Puppeteer

Execute JavaScript function on the page context of Puppeteer

Table of Contents

Introduction

When automating browser actions with Puppeteer, we often need to execute JavaScript code directly within the page context. This means that the code runs as if it were part of the page’s own script, giving us the ability to interact with the DOM, manipulate data, and perform complex actions.

Prerequisites

To follow this tutorial, you should have a basic understanding of Node.js and JavaScript. Additionally, you must have Node.js installed on your system as well as Puppeteer. Familiarity with async/await syntax in JavaScript is also beneficial.

Puppeteer Setup

Before you can execute any JavaScript function, make sure you have Puppeteer installed. You can add it to your project with the following command:

npm install puppeteer

Once installed, you can create a new Puppeteer instance and open a new page with:

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    // Your code here...
})();

Execute JavaScript Function

To execute a JavaScript function within the page context, you use the page.evaluate() function. This method can run any JavaScript expression or function inside the page’s context.

Example

Suppose you want to manipulate the DOM by changing the background color of the page. Here’s how you can do it with page.evaluate():

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://example.com');

    await page.evaluate(() => {
        document.body.style.backgroundColor = 'lightblue';
    });

    // Other actions...
    await browser.close();
})();

In the code above, page.evaluate() takes an anonymous function that sets the document.body.style.backgroundColor to ‘lightblue’. The function is serialized, sent to the browser, and run within the page.

 

Pass arguments to JavaScript function

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // Function to be executed in the page context
  const myFunction = (arg1, arg2) => {
    // Your logic here
    console.log(arg1, arg2);
    return arg1 + arg2;
  };

  // Arguments to be passed to the function
  const arg1 = 10;
  const arg2 = 20;

  // Execute the function in the page context and pass arguments
  const result = await page.evaluate((func, a, b) => func(a, b), myFunction, arg1, arg2);

  console.log('Result from page:', result);

  await browser.close();
})();

In this example, myFunction is a simple function that takes two arguments and logs them to the console. We then use page.evaluate to execute this function in the context of the page and pass the arguments arg1 and arg2. The result from the function execution is returned and logged.

Make sure to handle the promises properly using await since page.evaluate returns a Promise. Also, note that the function you pass to page.evaluate cannot directly reference variables from the Node.js environment; you need to explicitly pass them as arguments.

 

Conclusion

Executing JavaScript within the page context while automating with Puppeteer is straightforward with the page.evaluate() method. This powerful feature allows you to directly manipulate the DOM, interact with page scripts, and perform complex tasks as part of your automation script.

References