DEV Community

Benjamin Mock
Benjamin Mock

Posted on

6 2

πŸ“· 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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’