Categories
java javascript selenium selenium-webdriver webdriver

WebDriver’s executeScript returns text of alert instead of value returned from JavaScript method

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.