10

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);
2
  • What does js.executeScript() return? Javadoc clearly says One of Boolean, Long, String, List or WebElement. Or null.. Commented Aug 29, 2013 at 21:02
  • thats where (last line) its throwing nullpointer error Commented Aug 29, 2013 at 21:03

2 Answers 2

14

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);
Sign up to request clarification or add additional context in comments.

2 Comments

@Sudhakar Did it fail with a ClassCastException? Just change the type of your variable. Because it works for me.
Sorry I was wrong before. Yes your suggestion works perfectly. I had overlooked the important line One of Boolean, Long, String, List or WebElement. Or null. Thank you for your time. Appreciate it.
2

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

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

1 Comment

Yup the missing return was causing it for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.