To emulate a mobile device in Puppeteer, you can use the emulate
method on the Puppeteer Page
object. Here's an example of how you can emulate a specific mobile device:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Set the viewport size and user agent to emulate a mobile device
await page.setViewport({
width: 375,
height: 667,
isMobile: true,
hasTouch: true,
deviceScaleFactor: 2
});
await page.goto('https://www.example.com');
// Perform actions on the page
// ...
await browser.close();
})();
In this example, we are setting the viewport size to match that of an iPhone 6/7/8, setting isMobile
to true
, enabling touch events with hasTouch
, and setting the device scale factor to 2. You can customize these parameters to match the device you want to emulate.
Please note that setting the user agent alone does not fully emulate a mobile device, as the viewport size and touch events also play a role in how a website is displayed on a mobile device.