Basic Selenium

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

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class TestAlert {

    @Test
    public void TestAL() throws InterruptedException{

        // Load Firefox browser

         WebDriver driver=new FirefoxDriver();

       // Open KSRTC website

        driver.get("http://www.ksrtc.in/site/");

        // Maximize the window

        driver.manage().window().maximize();

        // Click on Search Availability Service button

        driver.findElement(By.xpath(".//*[@id='Table_3']/tbody/tr[1]/td[2]/div/a")).click();

        // Switch to alert window and capture the text and print

        System.out.println(driver.switchTo().alert().getText());

        // Pause testcase for 5 second

          Thread.sleep(5000);

        // click on ok button

        driver.switchTo().alert().accept();

        // Close browser

        driver.quit();
    }
}

 

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

public static void handleAlert(WebDriver ldriver){

           if(isAlertPresent(ldriver)){

           Alert alert = ldriver.switchTo().alert();

           System.out.println(alert.getText());

           alert.accept();

           }

           }

 

          public static boolean isAlertPresent(WebDriver ldriver){

                   try{

                   ldriver.switchTo().alert();

                   return true;

                   }catch(NoAlertPresentException ex){

                   return false;

                   }

                   }

 

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.

 

author-avatar

About Mukesh Otwani

I am Mukesh Otwani working professional in a beautiful city Bangalore India. I completed by BE from RGPV university Bhopal. I have passion towards automation testing since couple of years I started with Selenium then I got chance to work with other tools like Maven, Ant, Git, GitHub, Jenkins, Sikuli, Selenium Builder etc.

31 thoughts on “How to handle alert in Selenium Webdriver

  1. Trambak says:

    Hi Mukesh ,

    How to call this method do we need to create object of the class and then call the method and initialize the
    web driver first.
    or we need to do WebDriver driver= new ChromeDirver();

    Kiinldy let me know.
    Regards
    Trambak

    1. Hi Trambak,
      Without driver object, you cannot call driver methods. Without initialization, you will end up with NullPointerException so initialization is must as mentioned by you in statement

      1. Trambak Sinha says:

        Hi Mukesh,
        Ya I understood now
        Many thanks for the prompt reply.
        Regards
        Trambak

        1. Hi Trambak,

          Great…:)

  2. Vikas Vardhan says:

    Hi Mukesh,
    When we click on Create Post on FB, a pop-up comes.
    Is it an alert/dialog/window? And how to handle it in Selenium?
    I tried various ways, but no luck so far.
    Thanks,
    Vikas

    1. Hi Vikas,

      Create post pop up is on parent window itself so it doesn’t require to write any separate code to get control/focus on pop up.

  3. manohar says:

    Hi Sir, Can i use this Log4j.Properties file for any other Scripts

    1. Hi Manohar,

      Of Course…

  4. sumit says:

    sir this code is not working while working with chrome browser .plz suggest a code to handle with alert for chrome browser

    1. Sumit I just tried and worked.

  5. Surender says:

    HI Sir,

    Your explanation is awesome, it is very much helpful who wanted to become selenium automation tester.

    Regards,
    Surender

    1. Hey Surender,

      Thank you a lot. Happy weekend 🙂 Let me know if any help.

  6. Vikas says:

    If alert is modalDialog and it is present in iframe , how to handle this type of alerts .
    Alert alert = driver.switchTo().alert();
    alert.accept();
    is not working it is showing same error alert not present again and again.

    1. Hi Vikas,

      First switch to frame then accept the alert

  7. Shantosh says:

    Hi Mukesh,

    Please post part3 for data driven testing . Much waiting for it. Thanks a lot in advance
    Also your java tutorials are excellent mate please post topics on collections

    1. Hey Shantosh,

      Thanks

  8. Prakash says:

    Thanks Mukesh…

  9. Reshma Sultana says:

    Hi Mukesh,
    I can’t take a screenshot of the web page while alert box appears using selenium webdriver . How can i do it? please help.

    1. Mukesh Otwani says:

      Hey Reshma,

      try below code using ROBOT Class

      BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));

      ImageIO.write(image, “png”, new File(“c:\localdev\bla.png”));

      1. Reshma Sultana says:

        That code works perfectly.Thank you.

        1. Manoj Kumar says:

          Hi Reshma

          Would you share your entire code for this scenario here , it will be of great help for me

          Thank you

          1. Reshma Sultana says:

            Hi Manoj

            i replied to you with entire code 2 times but its not updated here.Sorry for inconveniences.

          2. Manoj Kumar says:

            Thanks reshma, not an issue, code is working fine now, because of improper package import i was unable to run the script

      2. Manoj Kumar says:

        Hello sir

        Not being able to execute above script , please do elaborate above code with an example ?

        Thank You

        1. Hey Manoj this is using Robot class in Java so it will capture complete screenshot it does not depends on browser.

          Hint for you please import the right package to make it work.

          1. Manoj Kumar says:

            Yes sir , now code is executable, package import issue only. Thanks a lot sir, Like your tutorials very much. Sir , can we execute scripts on given time.Suppose i want to send a message/mail at a particular time of day , on that time script should execute automatically and do the work for me?

  10. tinted glass says:

    Pretty section of content. I just stumbled upon your blog
    and in accession capital to assert that I acquire actually
    enjoyed account your blog posts. Anyway I’ll be subscribing to your feeds and even I achievement you access consistently fast.

      1. Sooraj Hat says:

        Hello i am a big fan of learn-automation.com. I am working on a project where i have a problem with firefox browser while handling alerts. As soon as i click on a delete button alert displays for a fraction of second and disappears. This problem only occurs on Firefox on chrome it works just fine. Even on firefox while manually clicking it works fine. Can you please give me a solution for this?

        1. Hi Sooraj,

          Thanks for such a nice comment. If possible can you please share the url as well so that I will check.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.