I'm using puppeteer to make a request to a web page and I've tried setting the view port to mobile device's as follows:
await page.setViewport({ width: 350, height: 700});
however, this doesn't get me the mobile site and instead I'm redirected to the desktop viewport site. When using chrome developer tools and I set it to iphone's viewport, I'm able to get the mobile version of the site.
Are there some headers I should be sending along with the age request in puppeteer to ensure I don't get redirected?
You might need to include isMobile: true
in your viewport options (page.setViewport()
) and set the user agent (page.setUserAgent()
) to match a specific mobile device. Puppeteer provides a convenience method to do both automatically with page.emulate()
.
Example:
const puppeteer = require('puppeteer');
const devices = puppeteer.devices;
const iPhone = devices['iPhone 6'];
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
await page.emulate(iPhone);
await page.goto('https://www.google.com');
// other actions...
await browser.close();
});
demo
You can also open, see, edit and define this devices yourself by editing the following file.
/node_modules/puppeteer/lib/DeviceDescriptor.js
you can see all available devices and select one of them or even define a custom one by yourself.
{
'name': 'CUSTOM NAME',
'userAgent': 'any useragent options you want',
'viewport': {
'width': 1024,
'height': 600,
'deviceScaleFactor': 1,
'isMobile': true,
'hasTouch': true,
'isLandscape': true
}
}
Just don't forget to
const devices = require('puppeteer/DeviceDescriptors');
const customDevice = devices['CUSTOM NAME'];
await page.emulate(customDevice);
The API seems changed in v5. Here is how to do it now:
const puppeteer = require('puppeteer');
const phone = puppeteer.devices['iPhone X'];
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.emulate(phone);
await page.goto('https://www.google.com');
// other actions...
await browser.close();
Check official API Doc
You can get all device names here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With