Handing Browser Alert Box Using Selenium Web Driver

26 / May / 2015 by Anurag Tiwari 0 comments

Recently while working on selenium I have come across in a situation where browser dialog box are the show stopper to validate ‘Login/Registration/Forgot Password etc.’ modules, though we are considering such cases as design issues.

However we need to deal with it to learn something new, fortunately I have got the solution to handle browser alerts.

Scenario – Assuming browser dialog box having only one button i.e. OK.



<em>WebDriver driver = new FirefoxDriver();
<em> driver.manage().window().maximize();
<em> driver.get("Site URL (Eg: www.google.com");
<em>driver.findElement(By.id("Enter you register id or any element")).click();

<em>driver.findElement(By.id("could be user name id")).sendKeys("XYZ");



<em>Alert alert=driver.switchTo().alert();
<em> System.out.println(alert.getText()); [This is only for output check]
<em> alert.accept();



To click on ‘Cancel’ button you can use – driver.dismiss();

Output – It will give you the exact text showing on your browser dialog box in console output.

Hope it will help you, Happy Learning!!


Leave a comment -