App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide Handling Alerts and Popups in Puppeteer

Handling Alerts and Popups in Puppeteer

By Manish Saini, Community Contributor -

Alerts and popup functions are widely implemented in online application forms on banking apps or ecommerce websites. Since automation testing has transformed, teams are searching for solutions that are simple to use and get precise results more quickly. These days, industries consider open source technologies because of their advantages. One such example is Puppeteer

Going ahead, let’s learn to set up the Puppeteer environment for handling alerts and pop-ups while integrating with BrowserStack.

What is Puppeteer?

Puppeteer is used to automate and streamlining the front-end development and testing, respectively. Microsoft first introduced it. Based on the Node.js library, Puppeteer is free and open-source software.

Executing the test cases on widely accessible numerous devices is made easier by responsive testing.

Puppeteer also boasts of a strong responsive community, with more than 60,000 GitHub starts. 

A few standout features include: 

  • It has APIs to interact with and control Chromium or the headless version of Chrome (following the protocols in DevTools). 
  • On browsers like Chrome, Chromium, Edge, and Firefox, it can also be utilized for non-headless execution.
  • The majority of user interface testing, keyboard input, mouse movement, and other tasks can be automated with Puppeteer. 
  • It can be used for testing Angular and Angularjs applications and for tasks like web page crawling and scraping.
  • Automated UI testing is used to verify ongoing application releases that comply with test cases.
  • Analyze runtime performance and performance timeline to verify performance concerns.
  • Reporting is made simpler by allowing users to save the automated execution video and create screenshots and PDFs.

Puppeteer for Browser Automation

The following are primary justifications for introducing Puppeteer for automating browser actions:

  1. Chrome is the primary focus right now. Although Puppeteer for Firefox is currently available, it is still in the experimental stage, and different browsers may enter the domain in the future. Therefore, we cannot state that it is a cross-browser automation testing tool. It utilizes chromium; therefore, Microsoft Edge is also compatible.
  2. Users can consider Puppeteer cross-browser testing to be a drawback. The Chromium Principles, which include its speed, stability, simplicity, and security, outweigh the drawbacks. 

Speed: ‘0’ performance overhead 

Stability: It has a solid implementation design.

Simple: It offers a simple user-interactive interface to understand, utilize, and troubleshoot.

Security: Since Puppeteer runs off-process using Chromium, it is safe to automate potentially harmful malicious web pages.

  1. Puppeteer is an API built on top of Chrome that aims to reduce incompatibilities. The Chromium version included with Puppeteer is distinct.
  2. To increase productivity, users can gain from promoting headless browser testing.
  3. It is built on an event-driven architecture.

Setting Up Puppeteer

Pre Requisites

  1. NodeJS must be installed since it is a JavaScript engine.
  2. A Code Editor is also needed. The most well-liked code editors for JavaScript are VS Code, Atom, and Sublime Text. However, we are using VS Code for this article.

Installation and Project Initialization for Puppeteer 

The steps below must be completed to install Puppeteer and set up a project of automated test cases for a web application:

Step-1: Create a directory for the project files 

Step-2: Open VS Code and import that directory into the editor. 

Step-3: Launch VS Code’s Terminal and enter the following command.

npm init

This utility will guide the creation of a package.json file

Step-4: Type “YES” to the question “Is this OK?” and hit the “Enter” key.

Step-5: Execute the command listed below to install Puppeteer. −

Or,

npm i puppeteer

Step-6: Execute the following command to install Puppeteer core. −

npm i puppeteer-core

Step-7: − Once Puppeteer and Puppeteer core has been installed, you can find the node_modules folder, package-lock.json file, and package.json file in the empty folder you made in Step 1.

Project Initialization for Puppeteer

Write your first Script

As an example, we will run a sample e-commerce website and take a screenshot. To begin, we must carry out the steps listed below:

Step-1: First, make a new file called example1.js in the directory.

Step-2: In this file, add the following code:

const pt = require('puppeteer');  //adding Puppeteer library

pt.launch().then(async browser => {  

   const p = await browser.newPage();  //browser new page

   await p.setViewport({ width: 1000, height: 500 })   //set viewpoint of browser page

   await p.goto('https://bstackdemo.com/'//launch URL

   await p.screenshot({    //capture screenshot

      path: 'bsdemo.png'

   });

   await browser.close()   //browser close

})

Step-3: Run the code by using the given command. −

node <filename>

Consequently, we will execute the following command in our example −

node example1.js

Step-4: You can see a new image bsdemo.png is saved in the project directory. On opening it you will see the screenshot of the website.

Write your first Script

Note: By default, Puppeteer runs in headless mode. For Headed execution, the user has to add one more argument {headless:false} with the launch function.

How to Handle Alerts and Pop-ups in Puppeteer?

Browser alerts can be handled via Puppeteer. After an alert has been displayed on the website, automation tools like Selenium and WebdriverIO accept or reject it.

However, before an alert shows on the page in Puppeteer, the user must specify whether to accept or dismiss it. For this, Puppeteer must be used to activate the on-event listener.

Methods for Handling Confirm Alerts

Here are a few ways to interact with Alerts −

  • accept(): Promise<void> − method to accept an alert.
  • message(): string − returns the message acquired from an alert.
  • type(): DialogType −  method to get the Dialog type. It can be prompt, confirm, or prompt.
  • dismiss(): Promise<void> − alert is dismissed using this method.

Code-Based Example

A confirm alert appears in the image below when the “Click me” button for “On button click, confirm box will appear” is clicked. We’ll get the alert’s text by using Puppeteer here, and we’ll accept it.

Code Based Example

We’ll start by making a new file in the directory. Say example.js, and then add the following code to the newly created file.

const pt= require('puppeteer'//Puppeteer library

async function confirmAlert(){  

   const browser = await pt.launch({headless:false})  //launch browser in headless mode

   const page = await browser.newPage();  //browser new page

   await page.setViewport({ width: 1920, height: 1080 });

   page.on('dialog', async dialog => {   //on event listener trigger

      console.log(dialog.message());  //get alert message

      await dialog.accept();        //accept alert

   })

   await page.goto('https://demoqa.com/alerts')     //launch URL

   const b = (await page.$x("//button[@id='confirmButton']"))[0]     //identify element with xpath then click

   b.click()

   await browser.close()   //browser close

After successful execution, “Do you confirm action?” will appear in the console as the confirm alert text.

Making new file in directory

BrowserStack Automate Integration with Puppeteer

It’s really simple to run the Puppeteer test suite on BrowserStack. First, our script requires BrowserStack credentials for execution. For that, we will set our credentials into the environment variables 

BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY as shown below:

export BROWSERSTACK_USERNAME="arjunsinha_AN654z"

export BROWSERSTACK_ACCESS_KEY="hysmkJJYir7aWu4gcrMS"

Also, we need to use puppeteer.connect to connect to the CDP endpoint at BrowserStack. The caps variable is used to send the additional parameters to BrowserStack so that the specific browser/OS combination can be assigned to our test.

After configuration, we can run the Puppeteer test on BrowserStack.

After execution, we can see the test results on the BrowserStack Automate dashboard. Visit View Puppeteer test results to learn more. 

'use strict';

const { strict } = require('once');

const puppeteer = require('puppeteer');

const expect = require('chai').expect;

(async () => {

  const caps = {

    'browser': 'chrome'// we can choose `chrome`, `edge` or `firefox`.

    'browser_version': 'latest'// supports v83 and above. we can choose `latest`, `latest-beta`, `latest-1`, `latest-2` and so on.

    'os': 'os x',

    'os_version': 'big sur',

    'build': 'puppeteer-build-1',

    'name': 'example1'// The name of our test and build

    'browserstack.username': process.env.BROWSERSTACK_USERNAME || 'johndoe_AN654z',

    'browserstack.accessKey': process.env.BROWSERSTACK_ACCESS_KEY || 'xyzxyz123abc123'

  };

  const browser = await puppeteer.connect({

  browserWSEndpoint:

  `wss://cdp.browserstack.com/puppeteer?caps=${encodeURIComponent(JSON.stringify(caps))}`,// That endpoint gives a `browser` instance based on the `caps` that we specified

  });


//The BrowserStack Configuration code ends here. Following this line is our test script.

pt.launch().then(async browser => {  

   const p = await browser.newPage();

   await p.setViewport({ width: 1000, height: 500 })

   await p.goto('https://bstackdemo.com/')

   await p.screenshot({

      path: 'bsdemo.png'

   });

   await browser.close()

})

Conclusion

Due to its swift dependability, and robust foundation, Puppeteer framework is the newest trend in automation testing. Compared to existing automated testing tools, it is considerably easier to grasp. This article demonstrates how easy it is to set up the Puppeteer environment, manage alerts and pop-ups, and integrate Puppeteer with BrowserStack.

Use Puppeteer with BrowserStack Automate

Tags
Automation Frameworks Automation Testing

Featured Articles

How to handle Alerts and Popups in Selenium?

How to start with Puppeteer Debugging

Curated for all your Testing Needs

Actionable Insights, Tips, & Tutorials delivered in your Inbox
By subscribing , you agree to our Privacy Policy.
thank you illustration

Thank you for Subscribing!

Expect a curated list of guides shortly.