How to get Asynchronous Javascript responses from Selenium Webdriver How to get Asynchronous Javascript responses from Selenium Webdriver selenium selenium

How to get Asynchronous Javascript responses from Selenium Webdriver


When you call execute_async_script, Selenium passes as the last argument to the JavaScript code the callback you must call to indicate that the asynchronous code is done executing, if you do not pass arguments after your script when you call execute_async_script, then this will be accessible as arguments[0] in the JavaScript. Whatever value you pass to this callback is what your execute_async_script will return so:

response = driver.execute_async_script("""    var done = arguments[0];    $(document).one('application:subapp:rendered',         function(){           done('foo');    });""")

In the code above I assign the callback to done. That's just the way I like to do it. Note how the value to which response will be set is set by calling done("foo").

Note also that I'm using .one() rather than .on(). I've discovered that Selenium (at least up to 2.45) does not ever consider an old callback created for execute_async_script to be "obsolete" so if there is any chance that your event can happen again after your JavaScript above has finished executing, then it will call the callback again, and Selenium will honor the call again. If you happen to have another execute_async_script running at that time, then this spurious call will terminate your other execute_async_script call with the return value "foo". I've had that happen in one of my test suites. It led to very bizarre failures.


Use arguments[0] as a callback:

driver.execute_async_script("""    $(document).on('application:subapp:rendered', arguments[0]);""")

See also (should help in understanding):