[英]Selenium Javascript executor returns null
I have the following JavaScript code returning null
when ran through Selenium JavascriptExecutor
. 通过Selenium JavascriptExecutor
运行时,我有以下JavaScript代码返回null
。 However, the same code when ran in Firefox developer console returned a value. 但是,在Firefox开发人员控制台中运行时,相同的代码返回了一个值。
function tmp(){
var attrb = jQuery(jQuery("[name='q']")[0]).attr('type');
if(typeof attrb !== 'undefined' && attrb !== false){
return attrb;
} else {
return '';
}
}
tmp();
The below is my WebDriver code with the JS the same as above: 以下是我的WebDriver代码,JS与上面相同:
JavascriptExecutor jsExec = (JavascriptExecutor)driver;
Object inpType =
jsExec.executeScript("function tmp(){...}tmp();");
System.out.println("Type: " + inpType);
Above outputs null
instead of "text" string. 上面输出null
而不是“text”字符串。 Any ideas? 有任何想法吗?
you need to use return tmp() instead of tmp() in executeScript() method. 你需要在executeScript()方法中使用return tmp()而不是tmp() 。 Find the related reference driver.executeScript() returns NullPointerException for simple javascript 找到相关的参考driver.executeScript()为简单的javascript返回NullPointerException
The problem is that you execute two statements in executeScript()
. 问题是你在executeScript()
执行两个语句。 The function definition of tmp() and the function call of tmp(). tmp()的函数定义和tmp()的函数调用。
I don't know the details, but the function definition seems to return null. 我不知道细节,但函数定义似乎返回null。
Since executeScript returns the first value that can be returned, it returns null. 由于executeScript返回可以返回的第一个值,因此它返回null。 If you don't define the function and write the code inline, it will work. 如果您没有定义函数并将代码内联编写,它将起作用。
JavascriptExecutor jsExec = (JavascriptExecutor) driver;
Object inpType = jsExec
.executeScript("var attrb = jQuery(jQuery(\"[name='q']\")[0]).attr('type');"+
"if(typeof attrb !== 'undefined' && attrb !== false)" +
"{return attrb;}" +
"else{return '';}");
System.out.println("-------------- Type: " + inpType);
This should print your expected value. 这应该打印您的预期值。
Edit: Also, your posted code doesn't escape the ""
around [name='q']
. 编辑:此外,您发布的代码不会逃避[name='q']
周围的""
。 This ends the string and causes syntax errors. 这会结束字符串并导致语法错误。
您应该在jsExec.executeScript(...)
返回的结果中添加一个return
语句
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.