Waiting for a webpage to fully load with JavaScript in Selenium

I am facing an issue where I need to wait for the page to fully load before executing a certain action. It is important for me that the loading circle on the browser tab stops spinning before proceeding. The current Ajax function I am using does not work consistently, especially when loading a new page. My function is based on jQuery:

JavascriptExecutor jsDriver = (JavascriptExecutor) webDriver;
boolean stillRunningAjax = (Boolean) jsDriver
        .executeScript("return window.jQuery != undefined && jQuery.active != 0");
return !stillRunningAjax;

If this returns false, I run it again.

However, even after my function returns true, the browser continues to load (with the loading circle spinning) for a few more seconds, sometimes even longer.

I have tried using implicitlyWait, but it interfered with my function and did not solve the problem.

Some suggest that there is no complete solution for this issue in Selenium. However, I believe there must be a way, perhaps through a JavaScript-based solution or something else.

Answer №1

Utilizing JavaScript to pause execution until the page fully loads:

void waitForLoad(WebDriver driver) {
ExpectedCondition<Boolean> pageLoadCondition = new
    ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver driver) {
            return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
        }
    };
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(pageLoadCondition);
}

If you are specifically waiting for an AJAX request to reveal a certain element on the page, you can directly wait for that element to be present.

WebElement myDynamicElement = (new WebDriverWait(driver, 10))
 .until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging pre-rendered HTML in Vue.js components for both parent and child elements

Currently, I am rendering all the HTML server-side and attempting to use Vue to set this HTML as the $el for two components. According to the lifecycle diagram, this should be possible. There is a parent Vue instance (which binds to #main) that contains a ...

Anticipating 'STRING', received 'EOF'

I am in the process of creating a config.gateway.json file for my Ubiquiti firewall and now I need to upload the file. When I try to run this configuration on jsonlint.com, I encounter the following issue: { "LOAD_BALANCE": { "description": "LO ...

Seamless Integration of jQuery Functions

I am in need of some assistance with passing a chain of jQuery methods into a function as an argument. The goal is to have dynamic methods executed on a DOM object. This functionality would be particularly useful for writing qUnit tests where centralizat ...

Fulfill the promise within the $stateProvider and proceed with utilizing the outcomes

I am facing an issue where I need to resolve a promise in a state provider so that I can use the results of the promise in another promise. I am a bit unsure about how to go about this. I tried the following approach: app .config(['$stateProvid ...

Tips for handling an Alert or Pop up on mobile devices with Selenium Android Driver

I am currently facing an issue in closing the Alert or Pop Up Window while automating a Web Application on an Android Mobile using Android WebDriver. The problem arises when I navigate to my app's URL (http://m.url.com) and encounter an Alert/Pop Up w ...

Troubleshooting: Why Won't My Basic JQuery POST Request Work?

Can someone help me figure out how to use JQuery to send a POST request and display the data in a PHP file? Here is the HTML file: <html> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> ...

Find elements within an array that include a specific string

I've got several URLs listed below Reach out What's the best way to extract only "www.example.com" ? Can this be done easily with jsoup? I have both relative and absolute URLs and I only need to extract them without the tags. ...

Custom Joi middleware in Express v4 is failing to pass the Request, Response, and Next objects

I am currently in the process of developing a unique middleware function to work with Joi that will be placed on my routes for validating a Joi schema. In the past, I have created middlewares for JWT validation without passing any parameters, and they wor ...

Validating Credit Card Expiration Dates in AngularJS Form

I recently started learning AngularJS and decided to create a credit card validator. I successfully implemented the Luhn Algorithm in a custom filter, but now I'm facing issues with validating the expiration date as well. The conditions for a valid ex ...

Minimize white spaces when validating input fields in a form using Javascript

I'm currently facing a challenge with JavaScript, specifically regarding achieving five tasks without using jQuery. Despite trying various RegExp codes, none have successfully worked for me so far. Let's begin with the first task (number 1): El ...

Dealing with error management in Transfer-Encoding chunked HTTP requests using express and axios

My current challenge involves fetching a large amount of data from a database in JavaScript using streaming to avoid loading all the data into memory at once. I am utilizing express as my server and a nodeJS client that retrieves the data using Axios. Whil ...

Tips for responding to and disabling a specific button in Vuetify.js after clicking the follow or unfollow button

I have a situation where I need to implement a functionality for a series of buttons with follow and unfollow statuses. When a user clicks on any button, I want the status to change after a brief delay and deactivation, followed by reactivation. For instan ...

What is the best way to create a navigation bar that opens on the same page when clicked?

Can someone help me figure out how to create a navbar that, when clicked, opens a small window on the same page like in this example image? ...

Tips for customizing standard data types in TypeScript

Currently facing a challenge where I need to update a global type. Specifically, I am looking to modify the signature of the Element.prototype.animate function to make it optional. This is the approach I attempted: declare global { interface Element { ...

React - Login page briefly appears while loading

Hello, I have built a React application that consists of a Login page, Loading page, and the main app itself. However, there is a small issue where after a user logs in, instead of smoothly transitioning to the Loading page until the data is loaded, the L ...

Enhance data granularity in Jquery Flot by zooming in as the user interacts

I'm currently working on creating an interactive chart that allows users to zoom in for a more detailed view of the data. For instance, when viewing data over a default zoom period of 3 months, there would be one data point displayed every 24 hours. H ...

Struggling to locate the "Button" element using Selenium in C#

Having an issue with my Selenium code trying to locate a button that only has the attributes "Value" and "type". When inspecting it, it appears like this: <input type="sumbit" value="login" /> View inspection image I attempted t ...

Utilizing GitLab CI and YAML to implement Selenium automation for Dotnet Framework 4.6.1

Currently, I am involved in developing a Selenium Automation project for a UnitTest Project within the Dotnet Framework 4.6.1 environment. Moreover, I am also integrating Gitlab CI using a shared runner. For this purpose, I have created a YAML file and sp ...

What causes parameters to be initially passed as undefined when sending them from one component to another, only to later arrive with the actual data intact

When passing properties from a parent component to a child component, my code gets executed before the properties arrive. This results in an error stating "Cannot read properties of undefined (reading 'map')". Why does this occur? https://i.ssta ...

Can these similar functions be combined into a single, unified function?

Currently, I have 3 functions - and more to come soon - that all perform the same task. However, they control different enumerated divs/variables based on which div triggers the mousewheel event. I am wondering if there is a way to condense these very si ...