Puppeteer - Handling Confirm Alerts



Puppeteer is capable of handling Alerts. The automation tools like Selenium, WebdriverIO, and so on, accept or dismiss an alert after it has appeared on the page.

However in Puppeteer, the user has to give direction whether to accept or dismiss an alert before it appears on the page. For this, the on event listener has to be triggered using Puppeteer.

Methods for Handling Confirm Alerts

Some methods to work with Alerts are listed below −

  • accept(): Promise<void> − This method is used to accept an alert.

  • message(): string − This method is used to yield the message obtained in an alert.

  • type(): DialogType − This method is used to obtain the Dialog type. A Dialog type can be a prompt, confirm or prompt.

  • dismiss(): Promise<void> − This method is used to dismiss an alert.

In the below given image, on clicking Click for JS Confirm, a confirm alert is displayed. Let us obtain the text on the alert.

JavaScript Alerts

To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as follows −

Step 1 − Create a new file within the directory where the node_modules folder is created (location where the Puppeteer and Puppeteer core have been installed).

The details on Puppeteer installation is discussed in the Chapter of Puppeteer Installation.

Right-click on the folder where the node_modules folder is created, then click on the New file button.

Node Module

Step 2 − Enter a filename, say testcase1.js.

Testcase1.JS

Step 3 − Add the below code within the testcase1.js file created.

//Puppeteer library
const pt= require('puppeteer')
async function confirmAlert(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage();
   //on event listener trigger
   page.on('dialog', async dialog => {
      //get alert message
      console.log(dialog.message());
      //accept alert
      await dialog.accept();
   })
   //launch URL
   await page.goto('https://the-internet.herokuapp.com/javascript_alerts')
   //identify element with xpath then click
   const b = (await page.$x("//button[text()='Click for JS Confirm']"))[0]
   b.click()
}
confirmAlert()

Step 4 − Execute the code with the following command.

node <filename>

So in our example, we shall run the command given below −

node testcase1.js
Command has been Successfully

After the command has been successfully executed, the confirm alert text - I am a JS Confirm gets printed in the console.

Advertisements