我想在java中执行javascript代码。所以我写了如下所示的代码。但在执行期间,它在中线失败。说错误是'缺失;在陈述之前'。
JavascriptExecutor js = (JavascriptExecutor)driver;
String g=(String) js.executeScript("var r = confirm('r u ready');"+"if(r==true) { Var b='ok'; } return b;");
System.out.println(g);
答案 0 :(得分:1)
您在变量声明中遇到问题,请将Var
替换为var
:
String g=(String) js.executeScript("var r = confirm('r u ready'); var b; if(r == true) { b='ok'; } return b;");
答案 1 :(得分:1)
"(function() {var r,b; r = confirm('r u ready'); if(r == true) { b='ok'; } return b;})()"
答案 2 :(得分:1)
如果您的目标是在关闭dilog之前阻止执行,那么您应该使用executeAsyncScript而不是executeScript。
以下是显示确认对话框并等待某人关闭它的示例:
WebDriver driver= new ChromeDriver();
driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);
driver.get("http://stackoverflow.com");
Boolean confirm = (Boolean)((JavascriptExecutor)driver).executeAsyncScript(
"var callback = arguments[0]; setTimeout(function(){ " +
" callback(window.confirm('Are you ready?')); " +
"}, 1);");
另一个显示提示对话框并等待某人键入一些文本并将其关闭:
WebDriver driver= new ChromeDriver();
driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);
driver.get("http://stackoverflow.com");
// display a confirm dialog and waits for someone to type some text
String prompt = (String)((JavascriptExecutor)driver).executeAsyncScript(
"var callback = arguments[0]; setTimeout(function(){ " +
" callback(window.prompt('Give me some text!')); " +
"}, 1);");
// display the text typed by the user
System.out.println(prompt);