• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Programming Languages
    • Java Tutorials
    • Python Tutorials
    • JavaScript Tutorials
  • Automation Tools and Different Tools
    • Web Automation
      • Selenium with Java
        • Selenium Basic
        • Selenium Advance
        • Selenium Realtime
        • Framework
        • Selenium Interview
        • Selenium Videos
        • Selenium with Docker
      • Selenium with Python
      • WebdriverIO
        • Selenium Webdriver C# Tutorial
      • Cypress
      • Playwright
    • TestNG
    • Cucumber
    • Mobile Automation
      • Appium
    • API Testing
      • Postman
      • Rest Assured
      • SOAPUI
    • testRigor
    • Katalon
    • TestProject
    • Serenity BDD
    • Gradle- Build Tool
    • RPA-UiPath
    • Protractor
    • Windows Automation
  • Automation For Manual Testers
  • Services
  • Online Training
  • Contact us
  • About me
  • Follow us
    • Linkedin
    • Facebook Group
    • Facebook Page
    • Instagram

Automation

Selenium WebDriver tutorial Step by Step

You are here: Home / Basic Selenium / How to handle alert in Selenium Webdriver

How to handle alert in Selenium Webdriver

September 27, 2016 by Mukesh Otwani 31 Comments

Handle Alert in Selenium

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.

 

Filed Under: Basic Selenium Tagged With: Alert in Selenium, Handle Alert in Selenium Webdriver, Handle alert Popup in Selenium

Reader Interactions

Comments

  1. Trambak says

    June 2, 2020 at 12:12 AM

    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

    Reply
    • Mukesh Otwani says

      June 2, 2020 at 2:36 PM

      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

      Reply
      • Trambak Sinha says

        June 2, 2020 at 11:08 PM

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

        Reply
        • Mukesh Otwani says

          June 3, 2020 at 2:08 PM

          Hi Trambak,

          Great…:)

          Reply
  2. Vikas Vardhan says

    June 14, 2019 at 3:42 PM

    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

    Reply
    • Mukesh Otwani says

      June 25, 2019 at 12:03 AM

      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.

      Reply
  3. manohar says

    February 4, 2017 at 4:35 PM

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

    Reply
    • Mukesh Otwani says

      February 5, 2017 at 2:42 PM

      Hi Manohar,

      Of Course…

      Reply
  4. sumit says

    October 15, 2016 at 1:35 PM

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

    Reply
    • Mukesh Otwani says

      October 16, 2016 at 12:50 PM

      Sumit I just tried and worked.

      Reply
  5. Surender says

    August 27, 2016 at 10:07 AM

    HI Sir,

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

    Regards,
    Surender

    Reply
    • Mukesh Otwani says

      August 27, 2016 at 3:10 PM

      Hey Surender,

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

      Reply
  6. Vikas says

    August 2, 2016 at 1:04 PM

    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.

    Reply
    • Mukesh Otwani says

      August 5, 2016 at 1:39 PM

      Hi Vikas,

      First switch to frame then accept the alert

      Reply
  7. Shantosh says

    July 12, 2016 at 7:55 PM

    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

    Reply
    • Mukesh Otwani says

      July 14, 2016 at 11:14 AM

      Hey Shantosh,

      Thanks

      Reply
  8. Prakash says

    July 2, 2016 at 3:19 PM

    Thanks Mukesh…

    Reply
    • Mukesh Otwani says

      July 2, 2016 at 3:20 PM

      Welcome Prakash

      Reply
  9. Reshma Sultana says

    April 28, 2016 at 6:36 PM

    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.

    Reply
    • Mukesh Otwani says

      April 28, 2016 at 7:13 PM

      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”));

      Reply
      • Reshma Sultana says

        April 29, 2016 at 10:00 AM

        That code works perfectly.Thank you.

        Reply
        • Manoj Kumar says

          April 29, 2016 at 2:09 PM

          Hi Reshma

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

          Thank you

          Reply
          • Reshma Sultana says

            April 30, 2016 at 5:57 PM

            Hi Manoj

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

          • Manoj Kumar says

            May 1, 2016 at 10:35 AM

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

      • Manoj Kumar says

        April 29, 2016 at 2:07 PM

        Hello sir

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

        Thank You

        Reply
        • Mukesh otwani says

          April 30, 2016 at 3:41 PM

          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.

          Reply
          • Manoj Kumar says

            May 1, 2016 at 10:32 AM

            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

    September 22, 2015 at 7:56 AM

    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.

    Reply
    • Mukesh Otwani says

      September 22, 2015 at 8:28 PM

      Thanks 🙂

      Reply
      • Sooraj Hat says

        December 1, 2015 at 12:33 PM

        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?

        Reply
        • Mukesh Otwani says

          December 2, 2015 at 1:07 AM

          Hi Sooraj,

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

          Reply

Leave a Reply Cancel 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.

Primary Sidebar

Free Selenium Videos

https://www.youtube.com/watch?v=w_iPCT1ETO4

Search topic

Top Posts & Pages

  • Selenium Webdriver tutorial for beginners
  • How To Fix Eclipse Autocomplete Or Code Suggestion In Eclipse
  • Selenium Webdriver C# Tutorial
  • WHAT ARE YOUR EXPECTATIONS FROM US?

Stay connected via Facebook

Stay connected via Facebook

Archives

Footer

Categories

Recent Post

  • API Testing Using Postman And RestAssured
  • Disable Personalise Your Web Experience Microsoft Edge Prompt In Selenium
  • How To Fix Error: No tests found In Playwright
  • How To Fix Eclipse Autocomplete Or Code Suggestion In Eclipse
  • Best and easy way to Group test cases in selenium

Top Posts & Pages

  • Selenium Webdriver tutorial for beginners
  • How To Fix Eclipse Autocomplete Or Code Suggestion In Eclipse
  • Selenium Webdriver C# Tutorial
  • WHAT ARE YOUR EXPECTATIONS FROM US?