简体   繁体   English

在Java中执行javascript代码时发生错误

[英]error occured while executing the javascript code in java

I want to execute javascript code in java. 我想在Java中执行javascript代码。 So I Wrote the code as shown in below. 因此,我编写了如下所示的代码。 But during execution it fails at middle line. 但是在执行过程中,它在中间行失败。 saying error as 'missing ; 称错误为'缺失; before statement '. 声明前'。

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);

您在变量声明中遇到问题,将Var替换为var

String g=(String) js.executeScript("var r = confirm('r u ready'); var b; if(r == true) { b='ok'; } return b;");
"(function() {var r,b; r = confirm('r u ready'); if(r == true) { b='ok'; } return b;})()"

If your goal is to block the execution until the dilog is closed, then you should use executeAsyncScript instead of executeScript. 如果您的目标是阻止执行直到关闭dilog,则应使用executeAsyncScript而不是executeScript。

Here is an example to display a confirm dialog and wait for someone to close it: 这是显示确认对话框并等待某人关闭它的示例:

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);");

And another one to display a prompt dialog and wait for someone to type some text and close it: 另一个显示提示对话框,等待某人键入一些文本并关闭它:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM