Hi. Welcome to trycoder.com where we teach and train on coding/development. If this is your first time visiting our website, I recommend you checkout our youtube channel and facebook group to get more from us.
In this tutorial, we will discuss how to get a mobile device view of a website without actually using a mobile phone. We will achieve this using a node JS library developed by Google called Puppeteer. If this is your first-time hearing about puppeteer, I recommend you check out our article on how to get started with puppeteer.Mobile device emulation is a very necessary task especially for web developers because a good look of a web page on mobile is very important. Apart from that, there are also many reasons why a developer would want to perform mobile device emulation.
NB: Ensure you have Node JS and puppeteer installed in your local machine.
As written on their official website, puppeteer is “headless chrome”, meaning it performs everything a normal browser does but except for the fact that, you don’t see it opening up and been done by a user.
So in mobile device emulation, puppeteer actually open up a website in a mobile browser just like a user will actually pick up his/her mobile phone, press chrome and navigate to a website.
We are going to write a short code where after opening the site in a mobile browser, puppeteer will take a screenshot and save in our local machine as proof.
Isn’t it awesome guys!!!
So developers can rather just run a script in few seconds and see how a website looks on mobile rather than picking up a mobile phone itself to do that.
Also, puppeteer provides features to get the mobile view from different types of mobile phones via its configuration. It can be configured to set a specific screen size, phone and much more.
Below is an example of opening a website on iPhone 6 and logs the page title on the console. The comments in the code explain the different lines.
server.js
const puppeteer = require('puppeteer')
const iPhone = puppeteer.devices['iPhone 6']; // set device type
(async () => {
const browser = await puppeteer.launch() //launch browser
const page = await browser.newPage() //new page/tab
await page.emulate(iPhone) //emulate device
await page.goto('https://go237.com/') //navigate to url
await page.screenshot({
path: './uploads/image.png', // set path and name of screenshot
fullPage: false
})
console.log(await page.title()) //log title of page
await browser.close() //close browser
})()
Run script and check uploads folder in your project directory.
OUTPUT
Thanks for reading!
Comments
Post a Comment
Please do not enter any spam link in the comment box.