Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

driver.executeScript() returns NullPointerException for simple javascript

js.executeScript("return document.title") works fine as expected but I'm not sure why my code returns null pointer error. what is wrong here?

   String testJs= "function test() {arr = 111; return arr;}; test();";
   JavascriptExecutor js = (JavascriptExecutor) driver;
   int a = (Integer) js.executeScript(testJS);
like image 917
Sudhakar Avatar asked Aug 29 '13 21:08

Sudhakar


2 Answers

This javascript

function test() {arr = 111; return arr;}; 
test();

Calls the method test() but doesn't do anything with the result, ie. doesn't return it to the caller.

So

int a = (Integer) js.executeScript(testJS);

will return null and try to be dereferenced which will fail because dereferencing null throws NullPointerException.

Javadoc for JavascriptExecutor.html#executeScript(java.lang.String, java.lang.Object...)

Maybe you want the javascript

function test() {arr = 111; return arr;}; 
return test();

This works for me

System.setProperty("webdriver.chrome.driver", "C:\\Users\\me\\Downloads\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
JavascriptExecutor executor = (JavascriptExecutor) driver;
String js = "function test() {" +
            "arr = 111; return arr;" +
            "}; return test()";
Long a = (Long) executor.executeScript(js);
System.out.println(a);
like image 59
Sotirios Delimanolis Avatar answered Sep 24 '22 03:09

Sotirios Delimanolis


Yeah, the key thing is not to forget insert the return, f.e.:

Long dateNow = (Long) jse.executeScript("return Date.now()");
like image 38
Andrii Bogachenko Avatar answered Sep 26 '22 03:09

Andrii Bogachenko