Is there a way to access the second hyperlink by opening it in a neighboring tab?

I have been experimenting with different methods to open a link in a newly opened tab, but so far none of them have been successful.

Below is a minimal and reproducible example with explanations of what happens after each line (this example uses Selenium webdriver in Java):

driver.get("https://twitter.com") //opens twitter in tab 1 (as intended)

((JavascriptExecutor)driver).executeScript("window.open('https://google.com')"); //opens a new tab (tab 2) and then navigates to google.com (as intended)
((JavascriptExecutor)driver).executeScript("window.location.replace('https://facebook.com')"); //unexpectedly opens facebook.com in tab 1

My goal is to have Facebook open in tab 2 instead.

Answer №1

If you start by launching https://twitter.com as the main URL, then proceed to open https://google.com in a neighboring tab. After that, open https://facebook.com in the same adjacent tab. You must implement the use of a WebDriverWait to ensure that numberOfWindowsToBe(2) before proceeding. Below is a sample solution:

  • Code Block:

    public class A_demo 
    {
        public static void main(String[] args) throws Exception 
        {
            System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.addArguments("start-maximized");
            options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
            options.setExperimentalOption("useAutomationExtension", false);
            WebDriver driver = new ChromeDriver(options);
            driver.get("https://twitter.com");
            String parent_window = driver.getWindowHandle();
            ((JavascriptExecutor) driver).executeScript("window.open('https://google.com');");
            new WebDriverWait(driver,5).until(ExpectedConditions.numberOfWindowsToBe(2));
            Set<String> allWindows = driver.getWindowHandles();
            for(String child_window:allWindows)
                if(!parent_window.equalsIgnoreCase(child_window))
                    driver.switchTo().window(child_window);
            driver.get("https://facebook.com");
            driver.quit();
        }
    }
    

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 is the process for enabling multiple consumers to subscribe to a shared topic in RabbitMQ and receive identical messages?

Although there is a similar question with an answer here, I remain uncertain whether the limitation lies in RabbitMQ's capabilities or if I simply need to conduct further research. Coming from a JS/Node background where the event pub/sub pattern func ...

JavaScript library for creating animated car movements on a map using JPG images

Looking for a way to animate a car's movement on a map? I have a map image in jpg format (not svg) and a sequence of (x,y) points ready to go! If you could recommend a JavaScript library that can help me easily create an HTML page with this animation ...

Utilizing Selenium in Python to Scroll within Inner Div: A Guide

Curious about how to scroll through the chats on web.whatsapp.com? Check out the pseudo-code below: recentList = driver.find_elements_by_xpath("//div[@class='_2wP_Y']") driver.execute_script("window.scrollTo(0, 500);") I'm eager to find a ...

Where can I find the link to access three.js on the internet?

Currently working on a JavaScript application within Google App Engine using three.js, but struggling to find the URL for online inclusion in my document. Uploading the entire large-sized three.js package is not ideal, so I'm looking for a way to obta ...

Transitioning the image from one point to another

I am currently working on a unique single-page website and I have been experimenting with creating dynamic background animations that change as the user scrolls. Imagine my website is divided into four different sections, each with its own distinct backgro ...

Adjust the height of a div in JQuery to fit new content after specifying a height previously

I have a division element with an initial height of 0 and opacity set to zero, its overflow is hidden, and it contains some content. <div style='height: 0px; opacity: 0px; display: none; overflow: hidden; border: 1px solid #000;' id='myd ...

Keep the link underlined until a different button is pressed

I need help with a webpage that displays a list of partners organized by categories. When clicking on sidebar categories, the link remains underlined. However, if you click anywhere else on the page, the link becomes inactive. CSS: button:hover { t ...

Is it possible to retrieve the vertices array from a QuickHull instance in three.js?

I'm currently working on generating a geometry using QuickHull from a THREE Mesh. However, it seems that the QuickHull object only contains information pertaining to the Faces of the mesh. Does anyone know if there is a way to access the vertex infor ...

Retrieve all items pertaining to a specific week in the calendar

I'm trying to obtain a list of week ranges for all data in my MongoDB. When a week range is clicked, only the records for that specific week range should be displayed. By clicking on the week range, the ID of the week (let's say 42, representing ...

Currently, my focus is on creating a robust slash command handler for discord.js version 13

I've been attempting to update my command handler to support slash commands, but I keep encountering an Invalid Form Body error when trying to activate the bot. I'm hesitant to switch handlers since I use this one for all my bots, but I can&apos ...

What is the best way to accomplish this task with promises (using the Q library)?

I am currently working on an app using express.js and mongodb. My goal is to fetch all posts if the database is available, otherwise an error will be thrown. I am utilizing the Q package for promises, but I am struggling to implement the desired functional ...

Tips for exporting 3D objects from 3ds Max Studio for optimal use in Three.js

I am facing an issue with loading a 3D object that I created in 3D Studio Max! When I export it as a .obj file (which generates two files, .obj and .mtl), I have tried using OBJMTLLOADET(), MTLLOADER(), and OBJLOADER() but none of them seem to work. Other ...

Is it possible to use Javascript to automatically calculate the number of characters in a form input box and then populate the form quantity input

I have successfully created a JavaScript function that counts the characters in a TextArea and displays the result in another TextArea. Now, I am faced with the task of adapting this function to work within an existing shopping cart form, where it is curr ...

Having trouble launching a Selenium session with Docker Compose?

I have been experiencing difficulties connecting to the selenium/chrome-standalone docker container as it is facing issues creating sessions. Every attempt leads to the same error message below: 21:02:35.263 WARN [SeleniumSpanExporter$1.lambda$export$3] - ...

Modifying the default text within a select box using jQuery

Within a select box identified as 'edit-field-service-line-tid', there is default text displayed as '-Any-'. This particular select field has been generated by Drupal. I am looking to use jQuery to change the text '-Any-' to ...

There seems to be an issue with the import class for React PropTypes. The prop

I have multiple oversized items that are utilized in numerous components, so I created a PropTypes file for each item. For example: PropTypes/PropLargeObject.js This file contains: import PropTypes from "prop-types"; const PropLargeObject = Prop ...

Transform Image on Hover in ReactJS

I am working on a Card Component that includes an image and text. Initially, the image is redImage and the text is black. When hovering over the card, I want the redimage to change to whiteimage and the text color to change to white as well. The content ...

Eliminate every instance using the global regular expression and the replace method from the String prototype

function filterWords(match, before, after) { return before && after ? ' ' : '' } var regex = /(^|\s)(?:y|x)(\s|$)/g var sentence1 = ('x 1 y 2 x 3 y').replace(regex, filterWords) console.log(sentence1) sentence2 ...

What is the best way to invert the positioning of the li elements to move upwards?

https://i.stack.imgur.com/mZaoS.png Seeking assistance on adjusting the height of bars to start from the bottom and go upwards instead of starting from the top position and going downwards. The JavaScript code below is used to generate the li elements and ...

Tips on locating the element within an anchor tag

I am completely new to using Selenium. I apologize if my question seems silly or naive. On a specific website, I have the following data. My main query is how can I extract the value of data-selectdate using Selenium with Python. Once I have the data-sele ...