Reputation: 133
My Javascript code in a HTML is as follows:
function CallMe(a,b){
alert("Hello");
var c = a + b;
return c;
}
and my Java Code for Selenium-WebDriver is as follows
JavascriptExecutor executor = (JavascriptExecutor)driver;
Object result = null;
try{
result = executor.executeScript("return(CallMe(5,4))");
driver.switchTo().alert().accept();
}catch(NoAlertPresentException ex){
System.out.println("Alert not found");
}
driver.manage().timeouts().setScriptTimeout(30,TimeUnit.SECONDS);
System.out.println(result.toString());
Now the output of the following java program is coming as "Hello" which is the text of the alert box whereas if I remove the alert box then the result is "9" which is what i expected.
Can someone suggest why the rest of the statements of the JavaScript are not executed when an alert box is encountered moreover I am accepting that alert box too in the Java code.
Also an alternate solution will be highly appreciated.
Upvotes: 3
Views: 1575
Reputation: 3765
alert()
blocks javascript execution until the alert is dismissed, so I am assuming that WebDriver's JavascriptExecutor decides to short-circuit and return the text of an alert box when one is encountered, rather than hang indefinitely as you are attempting to execute the entire script synchronously. This lets Java execution continue and allows the driver to switch to and close the alert box. At this point javascript would continue but webdriver is no longer receiving the result.
If you're curious, you could modify your function to show the execution halt as follows
function CallMe(a,b){
console.log('before alert at ' +new Date().toString());
alert("Hello");
console.log('after alert at ' +new Date().toString());
var c = a + b;
return c;
}
As a solution, you may want to use executeAsyncScript()
rather than executeScript()
to avoid the blocking problem, wait until the alert is displayed, close it, then retrieve the result of your javascript execution. See WebDriver executeAsyncScript vs executeScript and a wait as shown in the answer to Alert handling in Selenium WebDriver (selenium 2) with Java for instructions.
Upvotes: 1