Handing Browser Alert Box Using Selenium Web Driver

26 / May / 2015 by Anurag Tiwari 1 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!!


comments (1 “Handing Browser Alert Box Using Selenium Web Driver”)

  1. aseem dhawan

    Hi Anurag

    How would you click on any button other than OK and CANCEL on the dialog box? I have a Dialog Box that has a CANCEL and a DELETE Button.

    Your help will be highly appreciated.

    Thank you,


Leave a Reply

Your email address will not be published. Required fields are marked *