Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. It's often used for web scraping, automated testing of web pages, and taking screenshots or generating PDFs of pages.
Emulating devices in Puppeteer is quite straightforward, as Puppeteer ships with device descriptors for a variety of devices which can be used directly.
Here are the steps to emulate a device in Puppeteer:
First, you need to import the device descriptors. This can be done by requiring the
DeviceDescriptors
object from Puppeteer:const puppeteer = require('puppeteer'); const devices = require('puppeteer/DeviceDescriptors');
Next, you can select a specific device from the
DeviceDescriptors
object. For example, if you want to emulate an iPhone X, you would do:const iPhone = devices['iPhone X'];
Then, you can use the
page.emulate()
function to tell Puppeteer to emulate this device:const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.emulate(iPhone);
Lastly, you can navigate to your desired webpage and perform your usual Puppeteer tasks:
await page.goto('https://example.com'); // perform your actions here await browser.close();
Here is the whole code snippet:
const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');
const iPhone = devices['iPhone X'];
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.emulate(iPhone);
await page.goto('https://example.com');
// perform your actions here
await browser.close();
})();
This will make Puppeteer emulate an iPhone X when visiting "https://example.com".
Remember to replace 'iPhone X'
with the device you want to emulate. You can find a list of all available devices here.