nilima patil
nilima patil

Reputation: 9

How to handle multiple windows in selenium?

While automating via Selenium WebDriver, I have the below scenario. On a window, I copy the link and want to open the link on the new window(not in the new tab) and want to set focus on the new window. (Here the second window is not the child window of the first window)please help

Upvotes: 0

Views: 912

Answers (3)

user3636689
user3636689

Reputation: 1

//assume - multiple windows are opened by clicking link or a button.    
Set<String> windows = driver.getWindowHandles(); 
    
    for (String window : windows) 
    { 
       if (driver.getTitle().contains("***Something that is on new window***")) 
          { 
             driver.switchTo().window(window);
             //To get title of new window
             System.out.println(driver.switchTo().window(window).getTitle());
          }
    } 

Upvotes: 0

Mate Mrše
Mate Mrše

Reputation: 8394

In Selenium 4 (currently in beta), you the following will open a new window then automatically switch to the window:

  @Test
  public void openNewWindowForTestProjectBlog () {
    WebDriver newWindow = driver.switchTo().newWindow(WindowType.WINDOW);
    newWindow.get("https://blog.testproject.io/");
    System.out.println(driver.getTitle());
  }

Upvotes: 0

Rahul Das
Rahul Das

Reputation: 64

You can do something like this

WebDriver driverOne=new ChromeDriver();  
// navigate to your desired URL
driverOne.get("http://www.yourwebsite.com/");

// Do your stuff and copy the new link
// string newURL;

WebDriver driverSecond=new ChromeDriver(); 
driverSecond.get(newURL);

driverSecond will have a focus on the new window and once your actions are complete close the driverSecond.

Upvotes: 1

Related Questions