Wednesday, August 11, 2010

Deal with Javascript alert( ) and confrim( ) in WebDriver, as workaround

I posted one blog about Deal with "JS div DialogPane in WebDriver":
http://joychester.blogspot.com/2010/07/js-alert-handling-with-webdriver.html

Currently I met more dialog on different kind of page to deal with

<1> Javascript alert(msg)::
Most of time, I meet this situation when there is a validation on Front end. If you have to deal with this situation, one way to disable alert, before you click on a button which trigger the alert(), so that alert will not be triggered, while the validation always be there:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.alert = function(msg){};");

button.click();



<2> Javascript confrim(msg):
Here I will post an example how to simulate pressing "OK" button to deal with confirmation dialog.
First, find out the JavaScript which is sending a confirmation message by sniffer tool:

confirmed = confirm("Warning! This account is currently in use. Would you like to continue to login?");
if (confirmed)
{
this.document.forms[0].submitAction.value = "TERMINATE";
this.document.forms[0].submit();
}
else
{
this.document.forms[0].submitAction.value = "ABORT";
this.document.forms[0].submit();
}

function doSubmit(url, submitAction){

document.forms[0].action = url;
document.forms[0].target = "_self";
document.forms[0].submitAction.value = submitAction;
document.forms[0].submit();
}


Then, you may need to execute such bellowing javascript to simulate pressing "OK" button:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("javascript:doSubmit('/app/login.do','TERMINATE');");


instead of simple click() which will trigger the confirmation dialog:

login.click();


<3> The easiest Walkround:
I like the post on the Watir Wiki, which introduce "the Simplest way to stop JavaScript Pop Ups", the idea can be borrowed from that:
http://wiki.openqa.org/display/WTR/JavaScript+Pop+Ups
Hope this helpful!

Update:
WebDriver-Beta1 will have an implementation of the Alerts and Prompts API for the FirefoxDriver :)

1 comment: