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

Surprising Outcomes of Negative Margin in jQuery Animation

Unique Project Summary I am currently working on a website that incorporates a sliding menu feature. I have successfully implemented this functionality, and the display remains consistent during the animation transitions for sliding the menu in and out. T ...

What is the best way to calculate the width for each of the three elements in a row so that they all have 300px

Creating my own framework using flexbox has been an interesting journey. One of the major challenges I faced with flexbox is when dealing with an odd number of elements in a row, such as 3, 5, or 7. To tackle this issue, I decided to use JavaScript/jQuery. ...

Struggling to parse the JSON blob that was returned when using express-handlebars in node.js? Let

I am in the process of learning node.js and following a tutorial that involves making requests to the Accuweather API and receiving JSON data. Almost there ... but struggling with displaying the data: index.js const express = require('express' ...

Refreshing Bootstrap-Vue Table does not result in updating the table with table.refresh() method

I am facing an issue with a table that is supposed to be updating its data dynamically. The scenario is such that when a button is clicked in the parent component, a server call is triggered and a JSON file is loaded into a child component (the table) via ...

Managing OAuth2 redirections on the frontend: Best practices

I am currently working on implementing an OAuth2 flow for a Single Page Webapp, but I am facing challenges in dealing with Frontend/JavaScript redirects. Regarding the backend setup, I have it all sorted out: utilizing a library that takes care of everyth ...

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' ...

Checking the efficiency of Graphql API

Currently, I am in the process of optimizing key features within my Node.js API which incorporates GraphQL. This API serves as a proxy, receiving requests from various sources and forwarding them to multiple APIs based on the request. I am interested in ...

Implementing bidirectional data binding with Semantic UI's search dropdown feature in Vue.js

I'm currently facing an issue with the Semantic-UI searchable dropdown and Vuejs data binding. It seems like only one changed option is being model-bound, no matter which dropdown option I select. Here's a snippet of my code. I attempted to use ...

What is the meaning of MVVM "binder" and how is it used?

I've been conducting research online to gain a deeper understanding of the MVVM architecture in general. According to Wikipedia, the key components of the MVVM pattern are: Model View View Model Binder This is the first time I have come across the ...

Changing the click event using jQuery

My JavaScript snippet is displaying a widget on my page, but the links it generates are causing some issues. The links look like this: <a href="#" onclick="somefunction()">Link</a> When these links are clicked, the browser jumps to the top of ...

Prevent the need to go through the keycloak callback process each time the page is

I have integrated keycloak as an identity provider into my React application. I successfully added the keycloak react dependency via npm. Below are the versions of the keycloak react npm modules on which my application depends : "@react-keycloak/web ...

Executing all the trials within one browser using the TestNG WebDriver

Currently, my tests are set up so that each class instantiates its own browser. Each class corresponds to a specific page I want to test. Now, I aim for all my tests to run in a single browser. The code is structured as follows: there is a base page where ...

Tips for resolving the error message "How to fix TypeError: element_to_be_clickable() requires only one argument."

Encountering an error message that says TypeError: element_to_be_clickable() takes 1 positional argument but 2 were given while executing the code below: from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDrive ...

Discovering a hyperlink using Selenium: A step-by-step guide

Here's a question: How can I use the Selenium JAVA API to locate a link in the given scenario: The link does not have an ID There are numerous links, each with a unique href value I have some specific information (substring) about the href of the li ...

Triggering Submit Button Based on Checkbox Value in jQuery

Hey there, I'm encountering an issue. Let's say I have two types of checkboxes - one for person and one for company. If I submit the form without checking any of the person or company checkboxes, I want jQuery to display an alert. Otherwise, the ...

Unable to input any text using Selenium

In my document object model (DOM) structure, I have the following code: <?xml version="1.0" encoding="UTF-8"?> <div class="CodeMirror-scroll" tabindex="-1" draggable="true"> <div class="CodeMirror-sizer" style="margin-left: 53px; margin- ...

Diverse behaviors exhibited by an array of promises

I've developed a function that generates an array of promises: async addDefect(payload) { this.newDefect.setNote(payload.note); this.newDefect.setPriority(payload.priority); const name = await this.storage.get(StorageKeys.NAME); ...

Using node.js to send custom data over a websocket

I came across an excellent tutorial on websockets. In this tutorial, the server decodes and writes a message to the console whenever it receives a message from the client. After that, the server sends the message back to the client. var firstByte = data ...

Streamline the testing process to ensure compatibility with jQuery version 2.x

I currently have a substantial JavaScript code base that is all built on jQuery 1.8. I am planning to upgrade to jQuery 2.1 in the near future and I am fully aware that many parts of my code will likely break during this process. Is there any efficient me ...

What is the most effective way to transfer color values from one div to another?

When recreating a game similar to Mastermind, I encountered a challenge of copying color values from one div to another upon clicking a button. Despite browsing the web, I haven't found a solution for this specific situation. Below is the code I have ...