Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Selenium how to handle a new window?

I am writing a selenium script to login and create new mail, send it and logout. But when I click on New mail button, it opens a new window. In selenium how I can handle this. I am new to selenium. Please explain in detail.

like image 766
Darshana Avatar asked Oct 17 '22 08:10

Darshana


2 Answers

Use the below code, you have to use getWindowHandles- I hope it helps, Let me know in case you get stuck anywhere else -

 @Test
        public void multipleWindows() {
            driver.get(URL+"/windows");
            driver.findElement(By.cssSelector(".example a")).click();
            Object[] allWindows = driver.getWindowHandles().toArray();
            driver.switchTo().window(allWindows[0].toString());
            Assert.assertNotEquals(driver.getTitle(), "New Window");
            driver.switchTo().window(allWindows[1].toString());
            Assert.assertEquals(driver.getTitle(), "New Window");
        }
    }
like image 180
Avinash Pandey Avatar answered Oct 21 '22 07:10

Avinash Pandey


How to get Window Handle:
String handle = driver.getWindowHandle();
If there are multiple window gets opened when you click on any link,button etc... then to get "window Handle" of each window -
Set windowHandles = driver.getWindowHandles();

"getWindowHandles()" : method return window handle (unique id for each opened window) so that the return type is set. Because set will not contain duplicate elements so here getWindowHandles return unique id/window handles for each winodw and stored in Set.

How to switch to correct / appropriate window:
Basically there are two ways to switch to appropriate window.

  1. By using windowName driver.switchTo().window( "windowName" );
    OR
  2. To get current/parent/default window handle:

    String handle = driver.getWindowHandle();
    driver.switchTo().window( handle  );
    OR
    Set < String > windowHandles = driver.getWindowHandles();
    
    for(String handle : windowHandles )
     {
         driver.swicthTo().window( handle ); 
    }
    

Example of Handling Multiple Windows In Selenium

like image 22
Avinash Pande Avatar answered Oct 21 '22 07:10

Avinash Pande