DEV Community

Cover image for πŸ‘Ÿ Executing JavaScript in the page context of puppeteer
Benjamin Mock
Benjamin Mock

Posted on

πŸ‘Ÿ Executing JavaScript in the page context of puppeteer

So far we learned how to do Screenshots, how to create PDFs, how to set Cookies and how to click elements and type into pages using puppeteer.

Now we will learn how to execute our own JavaScript in a page context. In this example, we will again load the dev.to homepage, change the background by executing a JavaScript snippet and take a screenshot of the changed page.

First, let's make sure our snippet for changing the background color of the body of a page works. Just past that into the console.

document.body.style.background = "#000";
Enter fullscreen mode Exit fullscreen mode

dev.to darkmode

dev.to Darkmode ;)

And now let's look at the complete example:

// npm i puppeteer
const puppeteer = require('puppeteer');

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

  // let's navigate to the dev.to homepage
  await page.goto('https://dev.to');

  // evaluate will run the function in the page context
  await page.evaluate(_ => {
    // this will be executed within the page, that was loaded before
    document.body.style.background = '#000';
  });

  // and let's take a screenshot
  await page.screenshot({
    path: 'home.png',
  });

  // we're done; close the browser
  await browser.close();
})();
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
sajjadspg profile image
Sajjad Sarwar

Wanted to know can we execute the javascript code in the browser's console using puppeteer? If yes which method can be called to achieve the same?