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);
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);
Yeah, the key thing is not to forget insert the return, f.e.:
Long dateNow = (Long) jse.executeScript("return Date.now()");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With