Selenium waiting for page to load in Ajax rich applications

By Glib Briia on June 6, 2016

If it has happened that you are testing web application with lots of Ajax calls that makes parts or the whole pages to reload frequently you might find the code snippets below extremely useful.

In Ajax rich applications, when most of the pages refreshes through the means of Ajax calls, sometimes (in most cases) standard Selenium waitings work unstable or don’t work at all, so the use of custom waitings is often inevitable.

The below code snippet might be useful in those cases:

        public static void waitForJQueryProcessing(final WebDriver webDriver, int timeOutInSeconds) {
                new WebDriverWait(webDriver, timeOutInSeconds) {
                }.until(new ExpectedCondition<Boolean>() {
                        @Override
                        public Boolean apply(WebDriver driver) {
                                return (Boolean) ((JavascriptExecutor) driver)
                                                .executeScript("return window.jQuery != undefined && jQuery.active == 0");
                        }
                });
        }

Just using JavascriptExecutor and waiting for jQuery to become inactive can do the trick..

Also, in some cases it might be handy to explicitly wait for DOM to load and become interactive before performing any action:

        public static void waitForPageLoad(final WebDriver webDriver, int timeOutInSeconds) {
                new WebDriverWait(webDriver, timeOutInSeconds).until(new ExpectedCondition<Boolean>() {
                        @Override
                        public Boolean apply(WebDriver driver) {
                                return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete")
                                                || ((JavascriptExecutor) driver).executeScript("return document.readyState")
                                                                .equals("interactive");
                        }
                });
        }

Some more info about document.readyState could be found here http://www.w3schools.com/jsref/prop_doc_readystate.asp

Examples above are just the sample ones, there are numerous ways to customize them and possibly get even better results.