Sudhakar
Sudhakar

Reputation: 3094

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);

Upvotes: 10

Views: 16312

Answers (2)

Andrii Bogachenko
Andrii Bogachenko

Reputation: 1285

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

Long dateNow = (Long) jse.executeScript("return Date.now()");

Upvotes: 2

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280167

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);

Upvotes: 14

Related Questions