DEV Community

loading...
Cover image for πŸ‘Ÿ Executing JavaScript in the page context of puppeteer

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

benjaminmock profile image Benjamin Mock ・1 min read

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

Discussion (1)

pic
Editor guide
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?