DEV Community

Benjamin Mock
Benjamin Mock

Posted on

📷 More on Screenshots with JavaScript in Node.js (emulating devices)

In my last post I showed how to create a screenshot with puppeteer. In the example, I set the height and width of the viewport myself. But there's another option: you can emulate devices with puppeteer. So you can create screenshots as if they were taken on a device. Setting the device not only sets the correct viewport, but also uses the userAgent of this device. So you'll fetch a webpage as if you were on that device.

const puppeteer = require('puppeteer');

// get the full list of available devices.
console.log(puppeteer.devices);

// ...

// let's emulate an iPhone 6
await page.emulate(puppeteer.devices['iPhone 6']);

// there are also devices in landscape mode
await page.emulate(puppeteer.devices['Pixel 2 landscape']);
Enter fullscreen mode Exit fullscreen mode

Here's the complete code with device emulation

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

// we're using async/await - so we need an async function, that we can run
const run = async () => {
  // open the browser and prepare a page
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // it's better to emulate before going to the page, because otherwise a resize would happen
  await page.emulate(puppeteer.devices['iPhone 6']);

  await page.goto('https://codesnacks.net/');
  await page.screenshot({
    path: 'codesnacks.png',
    fullPage: true,
  });

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

// run the async function
run();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)