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.
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.
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
Mukesh Otwani says
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
Trambak Sinha says
Hi Mukesh,
Ya I understood now
Many thanks for the prompt reply.
Regards
Trambak
Mukesh Otwani says
Hi Trambak,
Great…:)
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
Mukesh Otwani says
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.
manohar says
Hi Sir, Can i use this Log4j.Properties file for any other Scripts
Mukesh Otwani says
Hi Manohar,
Of Course…
sumit says
sir this code is not working while working with chrome browser .plz suggest a code to handle with alert for chrome browser
Mukesh Otwani says
Sumit I just tried and worked.
Surender says
HI Sir,
Your explanation is awesome, it is very much helpful who wanted to become selenium automation tester.
Regards,
Surender
Mukesh Otwani says
Hey Surender,
Thank you a lot. Happy weekend 🙂 Let me know if any help.
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.
Mukesh Otwani says
Hi Vikas,
First switch to frame then accept the alert
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
Mukesh Otwani says
Hey Shantosh,
Thanks
Prakash says
Thanks Mukesh…
Mukesh Otwani says
Welcome Prakash
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.
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”));
Reshma Sultana says
That code works perfectly.Thank you.
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
Reshma Sultana says
Hi Manoj
i replied to you with entire code 2 times but its not updated here.Sorry for inconveniences.
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
Manoj Kumar says
Hello sir
Not being able to execute above script , please do elaborate above code with an example ?
Thank You
Mukesh otwani says
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.
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?
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.
Mukesh Otwani says
Thanks 🙂
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?
Mukesh Otwani says
Hi Sooraj,
Thanks for such a nice comment. If possible can you please share the url as well so that I will check.