How can I include mobile device details in headers when making a request?
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);
You can launch chrome with a custom useragent as follows:
const browser = await puppeteer.launch({
headless: false,
args: ['--user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/14A403 Safari/602.1'],
});