How to handle alert in Selenium Webdriver

In some application, while submitting a form or for confirmation a window comes that window known as Alert.Today we will talk about how we can handle alert in Selenium Webdriver using Alert Interface and using different methods.

Web-Based alert and Java Script alerts are same so do not get confused.

 

Until you do not handle alert window you cannot perform any action in the parent window.

Below is the screenshot of Alert window.

 handle alert in Selenium Webdriver

 

Youtube Video for handle alert in Selenium Webdriver

I generally prefer online video to start new because It gives me the clear picture what exactly we are doing so if you are Video lover like me then check out below tutorial and let me know your feedback on this.

 

 

We have to use SwitchTo method of Selenium which will allow us to control alerts.

Do you know we also use SwitcTo method to control frames and multiple windows as well. You might get this questions in your interviews as well like switchTo methods and what are the different ways to use SwitchTo methods.

How to Handle alert pop up in selenium Webdriver

To handle alert window in Selenium Webdriver we have predefined Interface known as Alert .

Check out official docs for Alert in Selenium Webdriver.
Alert Interface has some methods-

1- accept()- Will click on the ok button when an alert comes.

2- dismiss()- Will click on cancel button when an alert comes.

Note– Since alert is separate window so before using these methods we have to switch to alert window using switchTo() method

Scenario to –

Step 1-Open Firefox and open KSRTC website.

Step 2- Click Search Availability Service button.

Step 3- Capture the Alert text.

Step 4- Click on the OK button.

 

Program to handle alert in Selenium Webdriver

 

Output– Above program will capture alert text and will print on console

 

Above program will work perfectly for the condition where alert window comes always. Now consider a scenario where alert window comes when certain condition true for this we can create method which will check if alert window present then only it will execute otherwise it will skip this part

 

Sample code to create method

 

Important point- If alert in not present in the window and still we try to switchTo alert window then Selenium will throw NoAlertPresentException which will terminate your program so better you should use exception handle also in your script.

 

25 Comments

  1. manohar
  2. sumit
  3. Surender
  4. Vikas
  5. Shantosh
  6. Prakash
  7. Reshma Sultana
    • Mukesh Otwani
      • Reshma Sultana
        • Manoj Kumar
          • Reshma Sultana
          • Manoj Kumar
      • Manoj Kumar
          • Manoj Kumar