Thursday, July 28, 2011

Selenium - Handle Alert and Confirmbox

Handling alertbox.
Alertbox is special kind of modal dialog created though JavaScript. As it's modal dialog box the things in the parent window will not be accessible until close it.

selenium has getAlert()  method to handle javascript alertbox, It will click on the OK button of the alertbox and will return the text of the alertbox to verify. However Selenium fails to identify the alertbox if it has appeared through page load event. ( i.e. should not appeared when you navigate to some page or when refresh it).

Handle Alertbox at page load event
selenium is not able to indentify the dialogs appeard at the pageload event. look at this.
So I tried to click on the OK button with AutoIt script. I make the Autoit script, not a big, it's just three lines of code and tested it with both the browser and it did well. But when I call the same script (exe) from my testcase it fails to indentify the alertbox and my testcase failed. I am still finding out why the hell this is happening.
Following is the script to handle alertbox appeard at body load event.

$title = WinGetTitle($CmdLine[1]) ; retrives whole window title

Confirm box is a kind of alertbox with OK and Cancel button as compared to only OK button in alerbox.
Selenium provides following APIs to handle this.
chooseOkOnNextConfirmation() - This will click on the OK button if the confirm box appears after executing the very next step.
chooseCancelOnNextConfirmation() - This will click on the cancel button if the confirm box appears after executing the very next step.

You need to write down any of the above functions (depends on you requirement, ofcourse) just before the step which opens the confirmbox.
 * @author Gaurang Shah
 * Purpose: To handle Confirm box.
 * Email:
import org.testng.annotations.*;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class Handle_Alert {
private Selenium selenium;

public void startSelenium() {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "");


public void stopSelenium() {

public void handleAlert() throws Exception{"selenium_test");"Alert");
String a = selenium.getAlert();

public void handleConfirmBox() throws Exception {"selenium_test");
Download above file


harvest said...

After executing confirmation box getting error on executing further statements. My code is below.

System.out.println("Clicked on OK button in confirm box");
selenium.type("firstname", "firstname");//Getting below error here. Able to see output statement as it got executed.

ERROR: There was an unexpected Confirmation! [Press a button]
[java] at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(
[java] at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(
[java] at com.thoughtworks.selenium.DefaultSelenium.selectWindow(

Post a Comment