Home  Puppeteer   How to exec ...

How to execute java script in browser using puppeteer

In Puppeteer, the page.evaluate() function allows you to execute JavaScript code within the context of the current page in the browser. This function is powerful for interacting with and manipulating the DOM, retrieving data from the page, and triggering actions that simulate user interactions. Here are the key capabilities and use cases of page.evaluate():

Key Capabilities:

  1. Evaluate JavaScript in the Page Context:

    • page.evaluate() runs JavaScript code in the context of the page, just like in the browser's console.
  2. Access to Page DOM:

    • You can access and manipulate the DOM (Document Object Model) of the page. This includes selecting elements, modifying their properties or content, etc.
  3. Return Values:

    • The function passed to page.evaluate() can return values. These values can be basic types (like strings, numbers, booleans), arrays, objects, or even complex data structures.
  4. Handling Promises:

    • If the function passed to page.evaluate() returns a Promise, Puppeteer will wait for the promise to resolve and return its value.
  5. Serialization and Execution:

    • Arguments passed to page.evaluate() are serialized (converted into a JSON-safe format) before being passed to the browser context. This ensures compatibility and prevents side effects due to complex object references.

Use Cases:

Example Usage:

Here's a simple example demonstrating how page.evaluate() can be used to interact with the page:

const puppeteer = require('puppeteer');

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

  await page.goto('https://example.com');

  // Example: Retrieve the text content of the <h1> element on the page
  const pageTitle = await page.evaluate(() => {
    return document.querySelector('h1').textContent;
  });

  console.log('Page Title:', pageTitle);

  // Example: Click a button on the page using evaluate
  await page.evaluate(() => {
    document.querySelector('button').click();
  });

  // Wait for some time or events to settle
  await page.waitForTimeout(2000); // Wait for 2 seconds

  // Example: Extracting data and returning it from evaluate
  const pageData = await page.evaluate(() => {
    const data = {};
    data.username = document.getElementById('username').value;
    data.password = document.getElementById('password').value;
    return data;
  });

  console.log('Extracted Data:', pageData);

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

Notes:

By leveraging page.evaluate() effectively, you can automate interactions with web pages, extract data dynamically, and perform complex operations within Puppeteer scripts.

Published on: Jun 28, 2024, 12:15 AM  
 

Comments

Add your comment