Selenium gets caught in endless loops

On my homepage, I have a variety of links that lead to different applications. Each link opens a new tab or window, where I need to check for the presence of a specific element using its XPath (which is provided from an Excel file for all applications). After verifying the element's presence, I must close the child window and return to the parent window to repeat this process for the remaining 1000+ links. However, my script encounters issues if any of the applications fail to load or hang, preventing it from successfully closing the child windows and switching back to continue testing other links.

  • How does the page load function exactly?
  • I would like to automatically close the child window after a set number of seconds, even if the page is still loading, and then switch back to the parent window.

Answer №1

Once, I created a utility class that managed window handling and kept track of all the open window handles. With this class, the project was able to handle up to 4 open browser popup windows and close them in a specific order.

Check out the project here.

There is definitely room for improvement, but here is an example method from that class:

/**
 * Checks if WebDriver.getWindowHandles() returns any additional windows
 * that are not currently in the allHandles cache. If a new window is found,
 * it switches to that window and updates the allHandles cache.
 */
public static String handleNewWindow() {
    String newHandle = "";
    printHandles();
    Set<String> updatedHandles = driver.getWindowHandles();
    if (updatedHandles.size() < handleCache.size()) {
        mainHandle = "";
        LOGGER.info("Illegal state: A window was actually closed.");
        throw new IllegalStateException("This method handleNewWindow is not suitable\n" +
                "in this case. You probably want to use the updateHandleCache method.");
    } else if (updatedHandles.size() == handleCache.size()) {
        LOGGER.info("handleNewWindow() will do nothing because there are no new window handles.");
    } else {
        if (!updatedHandles.isEmpty()) {
            for (String windowId : updatedHandles) {
                if (!windowId.equals(mainHandle)) {
                    if (!handleCache.contains(windowId)) {
                        newHandle = windowId;
                        LOGGER.info("-- Open window handle: " + newHandle + " (new window)");
                    }
                }
            }
            if (!newHandle.equals("")) {
                LOGGER.info("Switching to new window.");
                driver.switchTo().window(newHandle);
            }
        } else {
            mainHandle = "";
            throw new IllegalStateException("No browser window handles are open.");
        }
    }
    handleCache = updatedHandles;
    return newHandle;
}

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

I am looking to retrieve a specific input value from a JSON array using JavaScript

I have created an array called 'PROPERTIES' which accepts values like username, password, sid, etc. I am looking to retrieve these entered values using JavaScript. 'PROPERTIES': {'gatewayurl': {'Name': ...

Automatically scrolling down a div as new content is added using XMLHTTPRequest.openConnection

https://jsfiddle.net/kv5gbamg/ - I created a jsfiddle to demonstrate the functionality of the system Essentially, I am seeking a way to automatically scroll the scrollbar to the bottom every time a new message is received. My system updates the div with ...

The Magnificent jQuery Widget Factory's _trigger Instance

When utilizing the _trigger function to initiate events, I often come across a recurring issue that I struggle to fully comprehend. The problem arises when there are multiple instances of my widget on the same page. In such cases, the most recently instan ...

Leveraging classes in Selenium for eliminating repetitive code

My task involves opening two websites that are essentially the same, but with different URLs, usernames, and passwords for logging in. Currently, I have two functions with duplicate code manually sending two different sets of user credentials. I would lik ...

An effective method for linking a value from one ng-model to another is by identifying and matching a specific string

I have been tasked with binding a value to one model based on the content of another model when it contains a string that starts with "https". For instance, there are two text fields each associated with a different model. <input type="text" ng-model= ...

Vue alert: The instance does not have a defined "hp" property or method, but it is referenced during rendering

Below is the code snippet that I am currently working with: var example1; var hp = ["p"]; document.addEventListener("DOMContentLoaded", function(event) { hp = ["x"]; example1 = new Vue({ el: '#example-1', data: { iLoveMysel ...

The Maven project encountered issues resolving dependencies due to the inability to locate the artifact with the coordinates com.mycompany.app:my-app:jar:1.0-SNAPSHOT

Issue Description I am currently working on a maven project with 2 modules, namely pageobjects-users and webdriver-tests-users. Being inexperienced in Java, I am struggling to resolve the following error: "Failed to execute goal on project pageobject-user ...

How to surround values and keys with double quotes using regular expressions in JavaScript

I am in need of a valid JSON format to request ES. I currently have a string that looks like this: { time: { from:now-60d, mode:quick, to:now } } However, when I attempt to use JSON.parse, I encounter an error because my ...

How can I resolve the issue of "require is not defined" in the code?

tag, you can find the following code snippet: Upon importing the 'mysql' module, an issue persists in the browser matching the error indicated by the title. Starting my journey into programming, I aim to develop a membership registration functio ...

Monitor modifications to an <input type="text"> element as its value is updated dynamically through JQuery from the server side

I am struggling with detecting when the value of an input field changes after it has been set by clicking a button. I have tried various events but can't seem to find the right one. <!DOCTYPE html> <html> <head> <script src=" ...

Display the option to "Delete" the link only when there are multiple images in my image collection

I am using jQuery and Ajax to remove banner images from my website. However, I want to make sure that if there is only one image left, it cannot be deleted. Each image in the list has a corresponding delete link: echo '<a class="delete j_bannerd ...

JavaScript attaching a function to an element within an array

Can anyone explain why I am unable to assign the toUpperCase method to a specific value in an array like shown below? I'm a bit confused because I thought objects were mutable and manipulated by reference. Maybe my understanding is incorrect? var ary ...

Chaining promises: The benefits of attaching an error handler during Promise creation versus appending it to a variable containing a promise

function generatePromise() { return new Promise((resolve, reject) => { setTimeout(reject, 2000, new Error('fail')); }); } const promise1 = generatePromise(); promise1.catch(() => { // Do nothing }); promise1 .then( ...

Managing a database update when server actions involve various form types

My UI dashboard contains multiple forms like "edit title" and "edit description", each with just one input element. I am looking to streamline database updates and server actions in next js 14, utilizing useFormState on the front end. While I have achieve ...

Ways to access a JavaScript object beyond the function scope

Using the code below, I am able to retrieve JSON data when an element is clicked. This data is then used to create a table, fill the cells with images, and append the table to a specific div. function LoadImagesByCategory() { $.getJSON("/Service/GetJs ...

What is the reason for not modifying the filtered and sorted data?

I am currently working on implementing filter options for an item list, but I am facing an issue where the filtering does not work when selecting dropdown options. Array in App.jsx const cameraShowList=[ {id:1,model:"Canon",title:"Canon ...

Framer Motion causes a crash in a Next.js application with the error message: "Unable to find named export 'useId'"

I am encountering an error in my Next.js app that I can't seem to trace back to its source. Strangely, the code triggering the error is not something I wrote myself. error - file:///Users/cheq/Desktop/cheqo/node_modules/framer-motion/dist/es/component ...

React splits the page and interrupts the scroll event listener

For some reason, my webpage has been split by the React.js library. When attempting to scroll down while hovering over the top navigation menu, scrolling becomes impossible. However, scrolling works fine when done on any other part of the screen. I' ...

Comparing Express.js View Engine to Manual Compilation

Currently, I am utilizing Express.js along with the hbs library to incorporate Handlebars templates in my application. Lately, I've delved into establishing a build system using gulp for my app and stumbled upon packages like gulp-handlebars. My query ...

The function Router.use() needs a middleware function, but instead, it received an undefined

Attempting to create an authentication app using Node.js, but encountering an error as described in the title. The code for app.js is already set up like this: var createError = require('http-errors'); var express = require('express'); ...