driver.executeScript() 为简单的 javascript 返回 NullPointerException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18520892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
driver.executeScript() returns NullPointerException for simple javascript
提问by Sudhakar
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?
js.executeScript("return document.title")
按预期工作正常,但我不确定为什么我的代码返回空指针错误。这里有什么问题?
String testJs= "function test() {arr = 111; return arr;}; test();";
JavascriptExecutor js = (JavascriptExecutor) driver;
int a = (Integer) js.executeScript(testJS);
采纳答案by Sotirios Delimanolis
This javascript
这个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.
调用方法test()
但不对结果做任何事情,即。不会将其返回给调用者。
So
所以
int a = (Integer) js.executeScript(testJS);
will return null
and try to be dereferenced which will fail because dereferencing null
throws NullPointerException
.
将返回null
并尝试取消引用这将失败,因为取消引用null
throws NullPointerException
。
Javadocfor JavascriptExecutor.html#executeScript(java.lang.String, java.lang.Object...)
Javadoc用于JavascriptExecutor.html#executeScript(java.lang.String, java.lang.Object...)
Maybe you want the javascript
也许你想要 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);
回答by Andrii Bogachenko
Yeah, the key thing is not to forget insert the return, f.e.:
是的,关键是不要忘记插入return,fe:
Long dateNow = (Long) jse.executeScript("return Date.now()");