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.
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.
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:
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 :
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
@Test public void testAlertOk() { //Now we would click on AlertButton WebElement button = driver.findElement(By.id("AlerButton")); button.click(); try { //Now once we hit AlertButton we get the alert Alert alert = driver.switchTo().alert(); //Text displayed on Alert using getText() method of Alert class String AlertText = alert.getText(); //accept() method of Alert Class is used for ok button alert.accept(); //Verify Alert displayed correct message to user assertEquals("this is alert box",AlertText); } catch (Exception e) { e.printStackTrace(); } }
So we can see that we have used
driver.switchTo().alert();
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
alert.accept();
For clicking on Cancel we need to use dismiss() method of Alert Class
alert.dismiss();
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
the same piece of code is working for IE and FF but it is not working for chrome browser
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.
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
and also the preoblem might be with my chrome browser version , mine is 26.0.1410.64 m
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…
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
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
@Neeraj
Please add some wait or sleep in your code before handling the pop up
Solved my problem..Nice Blog 🙂
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());
Please see the html code and try to find out whether it is a model alert or not. If it is alert then it should be handled by above code
Thanks for providing good article on “Handling JavaScript Alert in WebDriver”. http://reditblog.blogspot.in/
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.
That has been mentioned in post. To trim text u can use substring method of string that will help you to perform action
I have to mention an alert testcase before going to click edit button, can you please let me know how to do that