When it involves checking conditions on the browser side, all checks you'll be able to perform with execute_async_script are often performed with execute_script.
Even if what you are checking is asynchronous.
I know because once upon a time there was a bug with execute_async_script that created my tests fail if the script came results too quickly.
As far as I can tell, the bug is gone now since I've been using execute_async_script but for quite long before, I used execute_script for tasks where execute_async_script would have
been more natural.
For instance, performing a check that requires loading a module with RequireJS to perform the check:
driver.execute_script("""
// Reset in case it's been used already.
window.__selenium_test_check =
undefined
;
require(["foo"], function (foo) );
""")
result = driver.wait(lambda driver:
driver.execute_script("return window.__selenium_test_check;"))
The require call is asynchronous. The problem with this though, besides leaking a variable into the global space, is that it multiplies the network requests. Each execute_script call is a network request.
The wait method works by polling: it runs the test till the returned value is true.
This means one network request per check that wait performs (in the code above).
When you test locally it's not an enormous deal. If you've got to go through the network because you're having the browsers provisioned by a service like Sauce Labs, each network request slows down your test suite.
So using execute_async_script not solely permits writing a test that appears to be a lot of natural (call a callback, as we ordinarily do with asynchronous code, rather than leak into the global space) but it also helps the performance of your tests.
result = driver.execute_async_script("""
var done = arguments[0];
require(["foo"], function (foo) );
""")
The way I see it now is that if a test is going to look into the asynchronous code on the browser side to get a result, I use execute_async_script.
If it's going to do one thing for which there's no asynchronous method offered, I use execute_script.
If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, check out Intellipaat’s Selenium automation course!