Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I include mobile device details in headers when making a request?

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?

like image 522
andromeda Avatar asked Jun 16 '18 02:06

andromeda


3 Answers

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

like image 129
tony19 Avatar answered Oct 27 '22 09:10

tony19


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);
like image 5
Felix S. Avatar answered Oct 27 '22 10:10

Felix S.


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.

like image 4
HungryCoder Avatar answered Oct 27 '22 11:10

HungryCoder