我正在尝试实现一个我在网上找到的脚本,它自动将jQuery加载到当前没有它们的站点中。我正在使用Selenium Webdriver的JS Executor功能;但是,它会一直返回Null Pointer Exception。我试着到处寻找答案,但似乎无法理解发生了什么。是什么给了什么?
/** Browser automation driver for this test instance. */
private WebDriver driver;
/** JavaScript Executor for this test instance. */
private JavascriptExecutor js = (JavascriptExecutor) driver;
//...Firefox browser initialized here
public void JQuerify(final String Url){
ReporterNG.log("Opening a webpage at: " + Url);
driver.get(Url);
ReporterNG.log("Converting JS file to a String");
String jQueryLoader = getLoadJQuery();
// give jQuery time to load asynchronously
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
js.executeAsyncScript(jQueryLoader);
//THE PROBLEM ALWAYS OCCURS WITH THIS ^^^^^
ReporterNG.log("jQuery loaded!");
//THIS NEVER PRINTS OUT DUE TO THE ERROR ^^^^
}
/** dynamically load jQuery */
public static String getLoadJQuery(){
String LoadJQuery = "(function(jqueryUrl, callback) {\n" +
"if (typeof jqueryUrl != 'string') {" +
"jqueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js';\n" +
"}\n" +
"if (typeof jQuery == 'undefined') {\n" +
"var script = document.createElement('script');\n" +
"var head = document.getElementsByTagName('head')[0];\n" +
"var done = false;\n" +
"script.onload = script.onreadystatechange = (function() {\n" +
"if (!done && (!this.readyState || this.readyState == 'loaded'\n" +
"|| this.readyState == 'complete')) {\n" +
"done = true;\n" +
"script.onload = script.onreadystatechange = null;\n" +
"head.removeChild(script);\n" +
"callback();\n" +
"}\n" +
"});\n" +
"script.src = jqueryUrl;\n" +
"head.appendChild(script);\n" +
"}\n" +
"else {\n" +
"callback();\n" +
"}\n" +
"})(arguments[0], arguments[arguments.length - 1]);\n";
return LoadJQuery;
}
任何帮助都将非常感谢,因为我遇到了与JS Executor的其他类似应用程序相同的问题。谢谢!
答案 0 :(得分:1)
使JavascriptExecutor
实例成为该方法的本地实例。
JavascriptExecutor js = (JavascriptExecutor) driver;
// give jQuery time to load asynchronously
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
js.executeAsyncScript(jQueryLoader);