Home » Software Testing » Automation Testing » Selenium WebDriver Tutorial » How To Handle JavaScript Alert/Pop-Ups in Selenium WebDrive

How To Handle JavaScript Alert/Pop-Ups in Selenium WebDrive

Handling JavaScript Alert in Selenium WebDriver is big question if you have just started learning Selenium WebDriver. Because we always get multiple pop-ups and alert and some time we get information about validity of input and some time these pop-ups speaks about error, and also asks about user response.

But as a tester we need to verify the alert message and for the same we need to handle the Alert pop up. So its time to celebrate because Selenium WebDriver have provided us with Alert class to deal with JavaScript Alert In Selenium.

JavaScript Alert in WebDriver

Since I have created this alert through a basic html file and  it has one button Ok. So lets learn about all kind of javascript alerts present.

What is Alert In Selenium?

JavaScript Alert are most common information notification small window which grab the focus of all windows and intends end user to provide consent to proceed or cancel the changes.

So there are three common alert that we normally see in our day to day life

1- Plain Alert or Simple Alert: Such alert in Selenium Automation, Provides information to end user of recent change.

JavaScript Alert in WebDriver

Such alert comes with only OK button.

2- Confirmation Box: Such alert comes on screen with some information of change on page and it always comes with two buttons, First One OK and Second One Cancel. Such confirmation box, in general we see when we are deleting any information or updating any information or navigating away from the recent page to another without making any change.

Here is one example screenshot:

Confirmation Alert In Selenium

3- Prompt Alert : Such alert always appears with three fields, One textbox which wants input from end user and two buttons. One Ok and Another Cancel.

Here is one sample prompt alert :

Prompt Alert In Selenium


So lets learn handling of alert in selenium with one example and in this example I am taking Confirmation Alert.
Scenario :
Suppose we have one button, and once we hit on the button a alert appears with two button Ok and Cancel
a) In first case, Here end user clicks on Ok button

So we can see that we have used

This line of code is going to switch the cursor or focus from all windows to alert and here we can perform action on Alert In Selenium.

b) In second case we want to click on Cancel button
So above code would remain same only thing that would change in above script is

For clicking on Cancel we need to use dismiss() method of Alert Class

Hope this script is fruitful for you. This was my effort to share post on Alert In Selenium With Example.
Reference:
https://stackoverflow.com/questions/27841988/how-to-handle-javascript-alert-pop-up-window-in-selenium-webdriver

21 thoughts on “How To Handle JavaScript Alert/Pop-Ups in Selenium WebDrive”

  1. Pingback: Handling JavaScript Alert in WebDriver | Selenium Alchemy

    1. can you elaborate your problem…As per my understanding such anomaly should not come, because I have already tested this code for Chrome browser along with other Browsers.
      So please send me the stacktrace so that i could understand your chrome specific problem..

      Thank you and Hope to listen from you soon.

      1. I was trying to implement this on IRCTC site, soon after opening the application using chrome driver i simpliy clicked on login button without entering any uid, pswd so it is throwing an alert i was supposed to handle that alert using Webdriver. but when i am using the above code it is clicking on that button but after opening that alert the execution was not switched to the alert thats why my script execution was stopped there… and even in the log it is displaying unexpected alert open error message

  2. Hi,

    I was trying to implement this on IRCTC site, soon after opening the application using chrome driver i simpliy clicked on login button without entering any uid, pswd so it is throwing an alert i was supposed to handle that alert using Webdriver. but when i am using the above code it is clicking on that button but after opening that alert the execution was not switched to the alert thats why my script execution was stopped there…

    1. import java.util.concurrent.TimeUnit;

      import org.junit.Before;
      import org.junit.Test;
      import org.openqa.selenium.By;
      import org.openqa.selenium.WebDriver;
      import org.openqa.selenium.chrome.ChromeDriver;

      public class IRCTC {
      public WebDriver driver;

      @Before
      public void launch()
      {
      System.setProperty(“webdriver.chrome.driver”,”E:DD MISHRAworkspacechromedriver_win_26.0.1383.0chromedriver.exe”);
      driver = new ChromeDriver();
      }

      @Test
      public void test()
      {
      driver.get(“http://irctc.co.in”);
      driver.findElement(By.xpath(“//*[@id=’button’]”)).click();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      driver.switchTo().alert().accept();
      System.out.println(“Finally it click on Alert “);

      }

      }

      This code is working for me and hoping that it will help u in resolving your query

      1. Neeraj Srivastava

        Thanks for this but this code is not working for me, my Chrome version is 27.0.1453.110 m,

        Same issue I am facing, code got stuck at handle line, below is the err description:
        ===>
        org.openqa.selenium.WebDriverException: unknown error: unhandled inspector error: {“code”:-32603,”message”:”No JavaScript dialog to handle”}
        (Session info: chrome=27.0.1453.110)
        (Driver info: chromedriver=0.8,platform=Windows NT 5.1 SP3 x86) (WARNING: The server did not provide any stacktrace information)
        Command duration or timeout: 16 milliseconds
        Build info: version: ‘2.32.0’, revision: ‘6c40c18’, time: ‘2013-04-09 17:23:22’
        System info: os.name: ‘Windows XP’, os.arch: ‘x86’, os.version: ‘5.1’, java.version: ‘1.7.0_25’
        Session ID: b58f6213098f1ddf35ed7afececd31d2
        Driver info: org.openqa.selenium.chrome.ChromeDriver
        Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, rotatable=false, driverVersion=0.8, locationContextEnabled=true, version=27.0.1453.110, cssSelectorsEnabled=true, databaseEnabled=true, handlesAlerts=true, browserConnectionEnabled=false, webStorageEnabled=true, nativeEvents=true, applicationCacheEnabled=false, takesScreenshot=true}]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:187)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:569)
        at org.openqa.selenium.remote.RemoteWebDriver$RemoteAlert.accept(RemoteWebDriver.java:863)
        at TC_Home_Site.homeSite03(TC_Home_Site.java:469)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
        at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
        at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
        =========================

        Can you help me in this, is there any other thing is require to do this before handle the code.

        Please let me know on this,

        Thanks
        Neeraj

  3. Pingback: WebDriver’s most popular Commands | Abode QA

  4. Pingback: Handling Multiple Windows in WebDriver | Abode QA

  5. Pingback: Adding add-on in Firefox and Chrome using WebDriver | Abode QA

  6. Pingback: Email your failing Selenium WebDriver scripts’ Stack Trace to your Email Id | Abode QA

  7. Pingback: Unexpected error launching Internet Explorer. Protected Mode must be set to the same value | Abode QA

  8. Hello,

    I have an issue with chrome driver . I have put wait statements but still the pop up is not getting recognized as alert. Confirm Navigation alert in chrome with text “Are you sure you want to leave this page”

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

  9. As I want to copy the text from popup window and I have to trim the text and pass the value as the input in the next screen – pls help me out.

  10. I have to mention an alert testcase before going to click edit button, can you please let me know how to do that

Leave a Reply

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

Scroll to Top
%d bloggers like this: