2

I want to execute javascript code in java. 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);

3 Answers 3

1

If your goal is to block the execution until the dilog is closed, then you should use executeAsyncScript instead of 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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you brother, you correctly guessed what I was trying to do.
1

You have a problem in the variable declaration, replace Var with var:

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

Comments

1
"(function() {var r,b; r = confirm('r u ready'); if(r == true) { b='ok'; } return b;})()"

2 Comments

I expected the above statement returns output string as 'ok'. But it returns outpur as 'r u ready'. So how can I get output as 'ok'
Tip: to accelerate debugging run executeScript string inside the browser console))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.