English 中文(简体)
Puppeteer - Handling Confirm Alerts
  • 时间:2024-11-05

Puppeteer - Handpng Confirm Alerts


Previous Page Next Page  

Puppeteer is capable of handpng Alerts. The automation tools pke 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 pstener has to be triggered using Puppeteer.

Methods for Handpng Confirm Alerts

Some methods to work with Alerts are psted 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 cpcking Cpck 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-cpck on the folder where the node_modules folder is created, then cpck 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 pbrary
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 pstener 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 cpck
   const b = (await page.$x("//button[text()= Cpck for JS Confirm ]"))[0]
   b.cpck()
}
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