Can JavaScript talk to Selenium 2? Can JavaScript talk to Selenium 2? selenium selenium

Can JavaScript talk to Selenium 2?


You should look into the execute_async_script() method (JavascriptExecutor.executeAsyncScript in Java, IJavaScriptExecutor.ExecuteAsyncScript() in .NET), which allows you to wait for a callback function. The callback function is automatically appended to the arguments array in your JavaScript function. So, assuming you have a JavaScript function already on the page that waits until the condition you want, you could do something like the following (Java code below, C# and Python code should be similar):

String script = "var callback = arguments[arguments.length - 1];"    + "callback(myJavaScriptFunctionThatWaitsUntilReady());";driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);((JavascriptExecutor)driver).executeAsyncScript(script);

It might be possible to be even more clever and pass the callback function directly to an event that returns the proper data. You can find more information on the executeAsyncScript() function in the project JavaDocs, and can find sample code for this in the project source tree. There's a great example of waiting for an XHR to complete in the tests in this file.

If this isn't yet available in the version of the Python bindings available for use with SauceLabs, I would expect it to be available before long. Admittedly, in a sense, this is pushing the "poll for desired state" from your test case into JavaScript, but it would make your test more readable.


Theoretically it is possible, but I would advise against it.

The solution would probably have some jQuery running on the site that sets a variable to true when the JavaScript processing has finished.

Set selenium up to loop through a getEval until this variable becomes true and then do something in Selenium.

It would meet your requirements but it's a really bad idea. If for some reason your jQuery doesn't set the trigger variable to true (or whatever state you expect) Selenium will sit there indefinetly. You could put a really long timeout on it, but then what would be the different in just getting Selenium to do a getEval and wait for a specific element to appear?

It sounds like you are trying to overengineer your solution and it will cause you more pain in the future will very few additional benefits.


Not to be overly blunt, but if you want your App to talk to your Test Runner, then you're doing it wrong.

If you need to wait for an XHR to finish, you could try displaying a spinner and then test that the spinner has disappeared to indicate a successful request.

In regards to the animation, when the animation has completed, maybe its callback could add a class indicating that the animation has finished and then you could test for the existence of that class.