0

I am trying to understand the documentation for Selenium's executeAsyncScript here (https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/JavascriptExecutor.html) , for instance in their first example they have :

  long start = System.currentTimeMillis();
   ((JavascriptExecutor) driver).executeAsyncScript(
       "window.setTimeout(arguments[arguments.length - 1], 500);");
   System.out.println(
       "Elapsed time: " + System.currentTimeMillis() - start);

Now as far as I understand, the first argument is supposed to be a script, while the last one is a callback function, but in this example there is no callback, so what is going on here (arguments[] is empty right?).

If I wanted to have a function that returns a promise, and then print the promise, say doSomething().then(function(result) { return result;)}); how would this work with the executeAsyncScript function?

Thanks

1 Answer 1

3

You have to use the callback that the Selenium function provides you. Imagine that when you use executeAsyncScript that the script is wrapped in a Selenium function like this:

(function(args,,, callbackToServer){
    window.setTimeout(arguments[arguments.length - 1], 500);
})(args,,, callbackToServer);

As you can see arguments[arguments.length - 1] actually references callbackToServer function.

For example your promise would look like this:

doSomething().then(function(result) { 
    arguments[arguments.length - 1](result);
)});
Sign up to request clarification or add additional context in comments.

5 Comments

sorry but what Selenium function are you referring to?
See the example code. The first and third line are what the selenium function are accomplishing. The second line is what you injected.
Can you answer the second part of my question, I am horribly confused I'm afraid.
I updated your promise example. You will obviously have to keep track of the server callback. Perhaps set it to a variable.
So something like ((JavascriptExecutor) driver).executeAsyncScript("var callback = arguments[arguments.length-1]; doSomething().then(function(result){callback(result);}));");

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.