Discovering how to use the selenium-webdriver npm to navigate to a new window from a target="_blank" attribute

While trying to create a collection of selenium tests, I encountered an obstacle with the javascript selenium-webdriver npm package.

One specific test involves selenium verifying that a target="_blank" link functions properly by checking the content of the loaded page. However, I am unable to get selenium to switch focus to the new window.

After consulting the documentation and Stack Overflow, it appears that this code snippet should work:

driver.switchTo().defaultContent();

Unfortunately, this method does not achieve the desired result. The test script looks like this:

//1 load the URL
    driver.get( testConfig.url + '/britain/england/cornwall/hotelX' ).then(function(){
        //2 locate the link and click on it
        driver.findElement(By.css('.details-web')).click().then(function(){
            //3 wait for 10 seconds for the new window to open
            setTimeout(function(){
                //switch focus to the new window (current active window)
                driver.switchTo().defaultContent().then(function(){
                    //5 wait until the new element is visible
                    driver.wait( function(){
                        return driver.isElementPresent(By.css("#infinite-footer"));
                    }, testConfig.timeout).then(function(){
                        driver.close();
                        if( callback ){
                            callback( callback );
                        }
                    });
                });
            },10*1000);
        });
    });

I also came across this post: Selenium with Webdriver - Switch to child window without name However, it is written in Java, and my attempt to translate it to JavaScript was not successful.

Has anyone else been able to accomplish this using javascript selenium-webdriver?

Thanks, John

Following some advice from @Stanjer, I now encounter an issue where I receive an "undefined is not a function" error when attempting to run the forEach loop... or "ReferenceError: availableWindows is not defined."

//1 load up the url
        driver.get( testConfig.url + '/britain/england/cornwall/hotelX' ).then(function(){
            //2 find the link and click it
            driver.findElement(By.css('.details-web')).click().then(function(){
                var parent = driver.getWindowHandle();
                driver.sleep(1000);
                var availableWindows = driver.getAllWindowHandles();
                var newWindow = null;
                availableWindows.forEach(function(window) {
                    console.log( window );
                    if (window != parent) {
                        newWindow = window;
                    }
                });
                if (newWindow != null) {
                    driver.switchTo().window(newWindow);

                    driver.wait( function(){
                        return driver.isElementPresent(By.css("#infinite-footer"));
                    }, testConfig.timeout).then(function(){
                        driver.close();
                        if( callback ){
                            callback( callback );
                        }
                    });
                }
            });
        });

The console.log output of the availableWindows object:

{ closure_uid_233425945: 273,
  flow_:
   { events_: {},
     closure_uid_233425945: 1,
     activeFrame_:
      { events_: [Object],
        closure_uid_233425945: 29,
        flow_: [Circular],
        parent_: [Object],
        children_: [Object],
        lastInsertedChild_: [Object],
        pendingTask_: null,
        isLocked_: true,
        isBlocked_: false,
        pendingCallback: false,
        pendingRejection: false,
        cancellationError_: null },
     schedulingFrame_:
      { events_: {},
        closure_uid_233425945: 204,
        flow_: [Circular],
        parent_: [Object],
        children_: [Object],
        lastInsertedChild_: [Object],
        pendingTask_: null,
        isLocked_: false,
        isBlocked_: false,
        pendingCallback: false,
        pendingRejection: false,
        cancellationError_: null },
     shutdownTask_: null,
     eventLoopTask_: null,
     hold_:
      { _idleTimeout: 2147483647,
        _idlePrev: [Object],
        _idleNext: [Object],
        _idleStart: 410669389,
        _onTimeout: [Function: wrapper],
        _repeat: 有效回 },
     yieldCount_: 2 },
  stack_: null,
  parent_:
   { closure_uid_233425945: 271,
     flow_:
      { events_: {},
        closure_uid_233425945: 1,
        activeFrame_: [Object],
        schedulingFrame_: [Object],
        shutdownTask_: null,
        eventLoopTask_: null,
        hold_: [Object],
        yieldCount_: 2 },
     stack_: { [Task: WebDriver.getAllWindowHandles()] name: 'Task' },
     parent_: null,
     callbacks_: [ [Object] ],
     state_: 'pending',
     handled_: true,
     pendingNotifications_: false,
     value_: undefined },
  callbacks_: null,
  state_: 'pending',
  handled_: false,
  pendingNotifications_: false,
  value_: undefined }

Answer №1

To obtain an identical version of the code in JavaScript:

currentWindow = driver.getWindowHandle();

driver.sleep(1000);
var allWindows = driver.getAllWindowHandles();
var targetWindow = null;
allWindows.foreach(function(window) {
    if (window != currentWindow) {
        targetWindow = window;
    }
}
if (targetWindow != null) {
    driver.switchTo().window(targetWindow);
}

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

What strategies can be utilized to condense code when needing to adjust a className based on various props?

I am looking to condense this code, particularly the [if~else if] block, in order to dynamically change a className based on different props passed. export default function Button(props) { const { name, height, color, bgColor } = props; let className = ...

Is there a way to enable multiple selections in a particular section?

Currently, I am in the process of working on my step by step order and I want to express my gratitude for all the assistance I have received so far. Despite the help, I still have some unanswered questions! The steps in my project are categorized into dif ...

How Keyof can render an object undefined and prevent accurate verification

Encountering TS2532 error: Object is possibly 'undefined' while attempting to access an object's value by dynamically selecting the key. TypeScript seems to be restricting me from checking the field values, and I'm unsure of the underly ...

Loss of data in the local storage when the page is reloaded

click here to see image I have managed to save data to local Storage successfully, but it keeps disappearing when I reload the page. Can someone guide me on how to handle this issue? I am new to this and would greatly appreciate any help. Thank you. https ...

Creating a new array in Vue.js by filtering the results of a promise iteration

Is there a way to use the splice method to insert promise values from an old array into a new one for vue reactivity? I'm encountering an issue where the newArray remains empty and does not receive any values. Check out this link for more information. ...

The feature to toggle push notifications is missing in Xcode 11, and is also not available in the capability settings

I'm currently developing an Ionic project and trying to incorporate FCM Push notifications. I am unable to locate the toggle push notifications option in the signing & Capabilities tab in Xcode. ...

Exploring the Possibilities of Message Embeds in Discord using JavaScript

My goal is to teach my bot how to scan the description of embeds for a specific phrase. After reviewing the documentation at https://discord.js.org/#/docs/main/v11/class/MessageEmbed?scrollTo=description, it appears that I need to implement code similar to ...

Tips on sending a URL as a parameter via the command line in order to execute Python Selenium test scripts

Is it possible to pass a URL as an argument in CMD when running testcases.py? Currently, I am executing the following command in CMD to run the test cases of my Python file: python testcases.py "any url" The content of testcases.py is as follows: cla ...

JavaScript: Use onclick events to change the class of a div on multiple divs

I have a jQuery script that allows for toggling of the parent class when #icon is clicked. Additionally, when the body is clicked, it reverts back to the original class. Now, I'm looking to achieve the same behavior when clicking on #item5 or #item4 a ...

Deactivate interactive functions on the mat-slider while preserving the CSS styling

I'm attempting to create a mat-slider with a thumb label that remains visible at all times. Below is my mat-slider component: <mat-slider class="example-margin" [disabled]="false" [thumbLabel]="true" [tickInterval]="tickInterval" ...

How can we merge all the values of keys within an object into a new array using ES6?

My objective is to transform dynamic data into an array based on the keys of the toolset object, which does not have a constant number of keys. { toolset:{ info1:{ event-date:{}, event-time:{}, }, info ...

What steps can be taken to ensure Vue application admin page contents are not displayed without proper authentication?

By implementing role-based authentication in Vue app, we can efficiently manage routes and components visibility between regular users and administrators. As the number of roles increases, the application size grows, making it challenging to control CRUD ...

Rearranging components in React does not automatically prompt a re-render of the page

I'm currently working on a project to display the update status of my Heroku apps. The issue I encountered was that the parent component (Herokus) was determining the order, but I wanted them sorted based on their update dates starting from the most r ...

Obtain JSON data through an HTTP POST call

Here is a function that I have, which was mainly borrowed from the solution to another problem on SO: function sendPostRequest(url, data) { request( { url: url, method: "POST", json: true, body: data }, function(error, response, body) ...

Maintaining the footer and bottom section of the webpage

I am facing an issue with the footer on my website . I want the footer to always stay at the bottom of the page, even when I dynamically inject HTML code using JavaScript. The footer displays correctly on the main page , but it does not work as intended on ...

Finding the length of a filter in an AngularJS directive

I'm trying to figure out how to retrieve the value of filtered.length within my custom directive called my-dir. <li my-dir ng-repeat="result in filtered = (results | filter:query | orderBy: 'title')"> <h1>{{ result.title }}& ...

Combining Import and Require in a Node JS File

Having some trouble with the normalize-url package. It needs to be imported instead of required since it's not supported in ES module. I tried to work around this by adding some code I found online, but it doesn't seem to be fixing the issue for ...

Encountering a Module not found error with a ValidationError when trying to import an SVG file within a React

I've set up a manual Webpack 5 configuration for my React project with TypeScript. I am facing an issue while trying to import an SVG icon and using Material UI in the project. The error message I'm encountering is: Module not found: ValidationEr ...

The createElement function in Vue.js does not always return a fully formed component

There is a scenario where I need to create a functional component for a specific purpose. The task at hand involves taking all the children elements and adding some additional props to them, but only to those that are custom components of type ChildCompone ...

The functionality to open a new tab using Selenium in Python 3 seems to be malfunctioning

Recently, I included the following lines in my script to open a new tab. However, it seems to not be working anymore. body = driver.find_element_by_tag_name("body") body.send_keys(Keys.CONTROL + 't') If anyone could provide further assistance, ...