DEV Community

Cover image for Practical Puppeteer: How to emulate timezone
Sony AK
Sony AK

Posted on

Practical Puppeteer: How to emulate timezone

Hi everybody! Today Puppeteer topic will be about emulating timezone when accessing a web page. This feature available since Puppeteer version 2.0.0 and I think this API is very useful for testing or other use cases.

My use case would be testing data that has datetime information related to user's timezone when he/she access my website.

Now I just want to create a small script to test this nice feature. On Puppeteer, the API to emulate timezone is page.emulateTimezone(timezoneId). The scenario is we will set the timezone to Asia/Makassar (which is GMT+8) and we will go to website https://whatismytimezone.com to check the timezone emulation correct or not. Simple right?

Let's start.

Preparation

Install Puppeteer

npm i puppeteer
Enter fullscreen mode Exit fullscreen mode

The code

File emulate_timezone.js

const puppeteer = require('puppeteer');

(async () => {
    // set some options (set headless to false so we can see 
    // this automated browsing experience)
    let launchOptions = { headless: false, args: ['--start-maximized'] };

    const browser = await puppeteer.launch(launchOptions);
    const page = await browser.newPage();

    // set viewport and user agent (just in case for nice viewing)
    await page.setViewport({width: 1366, height: 768});
    await page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36');

    // emulate to Asia/Makassar a.k.a GMT+8
    await page.emulateTimezone('Asia/Makassar');

    // go to the web
    await page.goto('https://whatismytimezone.com');

    // close the browser
    // await browser.close();
})();
Enter fullscreen mode Exit fullscreen mode

As usual, I set the headless option to false so we can see the browser in action and I am not close the browser at the end of the script.

Run it

node emulate_timezone.js
Enter fullscreen mode Exit fullscreen mode

If everything OK then it will show information like below.

Alt Text

My timezone is GMT+7 and above screenshot is show GMT+8 (since we set timezone emulation to Asia/Makassar). It means the timezone emulation works perfectly.

Thank you and I hope you enjoy it.

Source code of this article available at https://github.com/sonyarianto/emulate-timezone-in-puppeteer.git

Reference

Top comments (0)