Advance Selenium

Handle Multiple Windows in Selenium Webdriver in Simple ways

We can handle multiple windows in selenium webdriver using Switch To methods which will allow us to switch control from one window to another window. If you are working with web applications then you must have faced this scenario where you have to deal with multiple windows.

If you have to switch between tabs then also you have to use the same approach.  Using the switch To method we can also handle frames and alerts with easy methods. I will focus on multiple windows as of now.

Before starting this section I will recommend you watch List and Set in Java which will help you to understand this concept in detail.

In Selenium, we have the feature that we can get the window name of the current window. In Selenium, we have the getWindowName method that will return the current window name in String form.

Note- Selenium 4 has a new feature where you can switch between tabs as well.

 

I have also published a video on this which will give you a clear idea how this works.

 

 

Approach to handle multiple windows in selenium webdriver

We also have getWindowNames, which will return Set<String> it means the set of window names then we can iterate using Iterator. The set is part of Java collection which allows us to handle multiple sets of data dynamically.

Scenario 1- In some applications, you will get some Pop up that is nothing but separate windows takes an example of naukri.com.
Therefore, in this case, we need to close the popup and switch to the parent window.

Complete program to handle multiple windows in selenium webdriver

First, we will switch to the child window (pop up window) then we will close it, and then we will switch to the parent window.

import org.testng.annotations.Test;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class TestNaukri {

@Test
public void TestPopUp() throws InterruptedException{
// Open browser
WebDriver driver=new FirefoxDriver();

// Maximize browser
driver.manage().window().maximize();

// Load app
driver.get("http://www.naukri.com/");

// It will return the parent window name as a String
String parent=driver.getWindowHandle();

// This will return the number of windows opened by Webdriver and will return Set of St//rings
Set<String>s1=driver.getWindowHandles();

// Now we will iterate using Iterator
Iterator<String> I1= s1.iterator();

while(I1.hasNext())
{

   String child_window=I1.next();

// Here we will compare if parent window is not equal to child window then we            will close

if(!parent.equals(child_window))
{
driver.switchTo().window(child_window);

System.out.println(driver.switchTo().window(child_window).getTitle());

driver.close();
}

}
// once all pop up closed now switch to parent window
driver.switchTo().window(parent);

}
}

 

We can switch to the window using title and content also.

If you still have some queries regarding this then comment in the below section.

Thanks for visiting my blog. Keep in touch.

Have a nice day.

author-avatar

About Mukesh Otwani

I am Mukesh Otwani working professional in a beautiful city Bangalore India. I completed by BE from RGPV university Bhopal. I have passion towards automation testing since couple of years I started with Selenium then I got chance to work with other tools like Maven, Ant, Git, GitHub, Jenkins, Sikuli, Selenium Builder etc.

69 thoughts on “Handle Multiple Windows in Selenium Webdriver in Simple ways

  1. Vinay Kumar Reddy D says:

    Hi Mukesh,

    I have a doubt that window handling process is same for both Page Object Model & normal method.

    1. Hi Vinay,

      Actually, window handling is nowhere related to POM or any other method. You can create a utility method to deal with such functionality

  2. Deepak says:

    Hi,

    I m facing an issue like driver.getWindowHandles() is returning only one value in IE eventhough multiple tabs are opened.

    Thank you.

    1. Hi Deepak,

      driver.getWindowHandles() returns a set of handles for individual windows not for tabs

      1. Atul says:

        How can we resolve this. Could you please explain.

        1. Hi Atul,

          You may need to wait for few seconds after clicking on link(which opens another window) then go ahead with getWindowHandles

  3. Garima says:

    Hi Mukesh

    Does driver remains same for parent and child window?

    1. Hi Garima,

      Yes, the driver object remains same for both windows. Using window.switchTo(), you can change the driver control to child window

  4. Umesh says:

    Hi Mukesh,

    having one pop up window on the screen and on that have two drop downs. So my question is i am not able to click on the drop down arrow or even not able to do set text. I tried multiple ways to find xpath’s but not working. So main problem is that the focus is not going on that popup. I stuck on this stage from long back but not getting any proper solution. I need your help to resolve this issue.

    1. Hi Umesh,

      What Selenium exception are you getting? Moreover, have you tried to check whether mentioned pop up is into some frame?

  5. Sunil K R says:

    can we handle the download popup (totally separate window that will not be on screen ) from IE in the same way i am having some issues. please help

    1. Hi Sunil,

      We cannot handle download pop up like window because it is not separate window. You need to handle it through desired capabilities for IE.

  6. Nibedita says:

    Hi Mukesh,

    I have one doubt.What if the getWindowHandles returns 5 window ID because there are multiple child window.But in this “if(!parent.equals(child_window))” line you are checking if parent is not equal to the child ,switch to the corresponding window id. what if at the first iteration i don’t get the expected window ID.I get the expected window ID in third iteration.
    Do we need to provided another if condition for matching the Title. Also is it required that a window will always have a Window ID.If not how do we handle this situation.

    Thank You.

    1. Hi Nibedita,

      Windows should definitely have unique window ids. Moreover in your case, as you mentioned, you can use window title as another if condition to switch to intended window.

      1. Nami says:

        Hi Mukesh.. 1qq.. since window handles are unique.. why are we storing it in set.. set will restrict duplicates but since handles are unique we can go with list rite? Pls clarify.

        1. Hi Nami,

          driver.getWindowHandles() return type itself is Set which is the default by Selenium library. So we need to save it into Set only…:)

  7. Mohamed Iburahimsha S says:

    Hi Mukesh
    I just want to know how to handle this below scenario,
    i have two windows, 2ndary windows has multiple pages(eg. 3 pages- login-1, main-2) and created object for each pages.
    Suppose if i want to switch over from 2ndary window-2nd main page to 1st window, How can i go there. ?
    Since windows handling be there at login page, once logged in successfully direction moved to main pages. Even we stored main windows in login page, How to pass the parent windows details(String hParent = driver.getWindowHandle()) to other main pages.

    1. Hi Mohamed,

      There are multiple ways to achieve this. Create separate class which you can call in test class which returns parent window handle and save it into some variable declared in test class or base class. Switch to second window then call page object methods corresponding to pages available in 2nd window. Similarly when you have to switch back top parent window, proceed same action in reverse order. This is one approach there are many other approaches and it depends how your framework is being developed. Always thinks in perspective of driver…:)

  8. Praga says:

    Hi Mukesh,

    I have implemented data driven testing framework.Now I am trying to implement parallel testing by adding ‘parallel=true’ in @dataprovider and in suite level I have defined as data-provider-thrrad-count=”4″.

    When I execute , 4 browsers initiated and after successful login , my test cases randomly getting filled with ‘no such exception’.

    But when I execute in sequential order, I am able to see my test case is getting executed without any exceptions.

    Please refer the below line of code :
    Suite:
    @dataprovider(parallel=true)

    Data driven testing I’m excell sheet with 5 different set of test data.

    1. Hi Praga,

      How you are reading excel file, is it into dataProvider annotated method or outside?

    2. Praga says:

      Dear Mukesh,

      I am reading excel file through dataprovider annotated method.

      Appologize for delayed reply.

      1. Hi Praga,

        This issue could be accessing same excel file by multiple threads. So have you created workbook object as singleton class?
        Also send me detailed error log

  9. QA says:

    The type Set is not generic; it cannot be parameterized with arguments

    1. Hi,

      Please change declaration to java.util.Set

  10. Rajat says:

    Hi Sir,

    How can i read a confirmation code from email and return to my Registration code window and put the confirmation code in registration selenium code?
    Grt thanks

    1. Hi Rajat,

      As of now, Selenium doesn’t provide any specific APIs which can do this job. You need to open webmail with usual selenium script and open that email and need to read content of email and save that Reg code to some variable. Now open your required web application and proceed with captured Code.

  11. Hi Mukesh,

    How to handle windows in the case when initially only two are opened and on clicking some link in second window, third is opened.
    ex – create gmail account page u click on learn more secon window is opened and when u click on security check in second third is opened.
    how to shift to third from second window after ur work in second window.

    1. Hi Deepthi,

      Here in this case, first get all window handles then switch to a window followed by condition like matching window title or any other element specific to intended window. If this condition satisfies then stay on same window otherwise navigate to next window and do check for same condition.

      1. Hi Mukesh
        But initially all the windows are not opened, third is opened only when u click a link on second window in that case how to handle the third window

        1. Hi Deepthi,

          Once you click on link, then go for getWindowHandles. It will return you set of 3 window handles.

  12. Ravi Gavkare says:

    Hello Mukesh,
    Scenario :
    1. Login the baseUrl.
    2. Used selenium authentication to login.
    3. Click on new link.
    4. New window open.
    5. Again asking the username and password in authentication window.

    Problem : Not able to login in the second window in the same test case.
    Error : org.openqa.selenium.NoAlertPresentException: No alert is active
    Could you please suggest on this?

    1. Hi Ravi,

      Authentication pop up is not an alert window. To handle this, use AutoIT or robot class. Check this link https://vistasadprojects.com/mukeshotwani-blogs-v2/handle-windows-authentication-using-selenium-webdriver/

  13. Akshay says:

    Hi Mukesh
    I need help that how can i switch from parent window to child to grandchild window to perform operation.

    1. Hi Akshay,

      If you are having more than 2 windows then getAllwindowHandles and switch to each window and verify any property such window title or any text on window and it should be unique to wrt each window. Once you are able to verify any attribute of your intended window, break loop.

  14. Ram S Mohapatro says:

    Hi Mukesh,
    Could you please help me to resolve below scenario :
    I have a parent window which contains a link,On Clicking the same 2nd window got opened. Same as 1st page this page has another link on clicking I am navigated to 3rd window.Now, My requirement is to close all the window in a sequence of 3->2->1.
    So, Please help me to get an Idea how to use collection wisely to handle such scenarios?

    Thanks in advance.

    1. Hi Ram,

      Role of collection i.e. Set is what you will be using for windowHandles. You can use iterator interface to iterate each window one by one. As you said, you want to navigate 3->2->1, so when your diver is on window 3, call driver .close() there then switch driver control to another window but you need to put one verification like window title equals to some value. Because based on window title or any other property, you can navigate to required window.

  15. vinod singh says:

    Hi Mukesh,
    I need one help. the scenario is I have to write any text into text area and double click on it to select it so that user can modify the text. I need to verify whether text is selected or not after double click on it. pls suggest any way to do it if possible through Selenium webDriver.
    Thanks in advance!!

    Vinod Singh

    1. Hi Vinod,

      Do sendKeys first, after this I hope cursor will remain inside input textbox. Now do doubleClick using Actions class so that whole text should get select. Use keys.chord via actions class and do Control + C so that whole text should get saved to system clipboard. Finally you can assert string which you passed via sendKeys operation and content of clipboard.

  16. Pushparaj R says:

    Hi Sir,
    Can u share the clear selenium syllabus topic by topic.
    Thank you very much…

  17. Rekhanadh says:

    Hi Mukesh,
    I have 4windows,i want to switch to all windows.How to write code.

    1. Hi Rekhanadh,

      Grab all windows handles into a set. Then iterate one by one

  18. swetha says:

    how to handle customizes dialogue boxes Actually in my project to display notifications they are using their own dialogue boxes w to handle those using selenium webdriver

    1. Hi Swetha,

      Check whether you are able to handle those dialogue boxes simply using driver. Also check those dialogue boxes are coming up inside a frame.

  19. Yamuna says:

    Hi Mukhesh,
    I have purchased your selenium hybrid framework and interview questions course and trying to run the test cases shown in your video. but i am getting below null pointer exception error. Test case code is same as given in your video. Please let me know how to resolve this error.
    FAILED: testHomePage
    java.lang.NullPointerException
    at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
    at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
    at com.sun.proxy.$Proxy7.click(Unknown Source)
    at Pages.HomePage.clickOnSigninLink(HomePage.java:31)
    at testcases.VerifyHomePage.testHomePage(VerifyHomePage.java:34)
    HomePage code:
    package Pages;

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;

    public class HomePage {

    WebDriver driver;

    public HomePage(WebDriver ldriver){
    this.driver= ldriver;
    }

    @FindBy(xpath=”//a[text()=’Sign In’]”) WebElement signInLink;

    @FindBy(xpath=”//a[text()=’My Account’]”) WebElement myAccountLink;

    @FindBy(xpath=”//a[text()=’My cart’]”) WebElement myCartLink;

    @FindBy(xpath=”//a[text()=’Checkout’]”) WebElement checkOutLink;

    public void clickOnSigninLink(){

    signInLink.click();
    }

    public void clickOnMyAccountLink(){

    myAccountLink.click();
    }

    public void clickOnMyCartLink(){

    myCartLink.click();
    }

    public void clickOnCheckOutLink(){

    checkOutLink.click();
    }

    public String getApplicationTitle(){

    return driver.getTitle();

    }
    }
    Verify home page code:
    package testcases;

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.support.PageFactory;
    import org.testng.Assert;
    import org.testng.annotations.AfterMethod;
    import org.testng.annotations.BeforeMethod;
    import org.testng.annotations.Test;

    import Factory.BrowserFactory;
    import Factory.DataProviderFactory;
    import Pages.HomePage;

    public class VerifyHomePage {

    WebDriver driver;

    @BeforeMethod

    public static void launchUrl(){

    WebDriver driver= BrowserFactory.getBrowser(“firefox”);

    driver.get(DataProviderFactory.getConfig().getApplicationUrl());
    }

    @Test
    public void testHomePage(){

    HomePage home= PageFactory.initElements(driver, HomePage.class);

    String title= home.getApplicationTitle();

    System.out.println(title);

    Assert.assertTrue(title.contains(“Demo Store”));
    }

    @AfterMethod

    public static void tearDown(){

    BrowserFactory.closeBrowser();

    }

    }

    1. Hi Yamuna,

      In your test case make below changes.

      Old code

      WebDriver driver= BrowserFactory.getBrowser(“firefox”);

      New Code

      river= BrowserFactory.getBrowser(“firefox”);

      1. Nikhil Sonawane says:

        Hi Mukesh,
        AS I’m facing same problem not able to set Firefox rofile prefernce as we have our devcode repo not allowed to set it. And it gives and JSON serilization error. So is any other way to handle Save file pop ?

        1. Hi Nikhil,

          In this circumstances, give a try to robot class.

  20. Sanjana sanz says:

    Thank you for the code. I used it in my live project.

    1. Hi Sanjana,

      Happy to read from you…:)

      1. Anil says:

        What are the errors/issues we can get during execution of our code with jenkins.
        ******please reply*****

        1. Hi Anil,

          There loads of error happens when you don’t configure Jenkins as per your requirements. Errors/Exceptions can be thrown while compilation/execution of code, Errors relating plugins of Jenkins, Error while cloning code from repository, Environment setup issues….so on. There is no specific numbers of error/issue which can be defined over here.

  21. priya says:

    hello Mukesh,

    I have one parent then child window, after child window want to handle some button in 3rd window as well, what is the code for 3rd window please help me out

    1. Hey Priya,

      You can use index to switch to specific window.

  22. Thejdeep G says:

    Hi Mukesh,

    For the application what am working…once i open the site…it will open a pop up window asking for user name and password…and the problem is …it cannot be opened through FF. It should be opned only through IE. am facing issues feeding data from excel to application. Can you please help me out on this? Am a beginner trying to do something…so please let me know

  23. Manali says:

    Hi Mukesh,Please let me know the code to handle more than 1 child window. For e.g when you click on the parent window multiple child windows open and to handle multiple child windows when clicked on the child window

    1. HI Manali,

      Below post will guide you http://design-interviews.blogspot.in/2014/11/switching-between-tabs-in-same-browser-window.html

      I actually like the concept of indexing. Just give a try.

  24. Rajiv kumar says:

    Hello Mukesh, i want to knw how can we close an advertisement popup using selenium. Moreover that advertisement is coming while i m running my script through eclipse, otherwise it is not coming. The url which i used is “http://www.hdfcbank.com/”.
    Please help me out..
    Thank you in advance.

    1. You can easily click on cross symbol.

      1. Rajiv kumar says:

        Can i do it by using selenium webdriver..

        1. Rajiv kumar says:

          Its an advertisement popup and i am not getting any xpath or others . This is what i am getting.. “” and i want to close this.

          1. Which app you have tried?

        2. Yes Rajiv you can do.

  25. Raghu Nandan says:

    package handleWindow;

    import java.util.Iterator;
    import java.util.Set;
    import java.util.concurrent.TimeUnit;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.testng.annotations.Test;

    public class HandleMultipleWindow {

    @Test

    public void handleWindow() throws InterruptedException

    {

    WebDriver driver=new FirefoxDriver();

    driver.manage().window().maximize();

    driver.get(“https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ltmpl=default”);

    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    String parent_window=driver.getWindowHandle();

    System.out.println(“Before switching Title is : “+driver.getTitle());

    driver.findElement(By.xpath(“//a[@href=’https://support.google.com/accounts/answer/1733224?hl=en’]”)).click();

    Set s1=driver.getWindowHandles();

    Iterator i1=s1.iterator();

    while(i1.hasNext())

    {

    String child_window=i1.next();

    if(!parent_window.equalsIgnoreCase(child_window));

    {

    driver.switchTo().window(child_window);

    Thread.sleep(3000);

    }

    }

    System.out.println(“After switching Title is :”+driver.getTitle());

    driver.close();

    driver.switchTo().window(parent_window);

    System.out.println(“Back to parent window :”+driver.getTitle());

    }

    }

    1. What is your doubt here?

  26. Mukesh says:

    Hi Mukesh,

    I have a case,

    I need to click a link in Window 1,which will route me to Window 2.Now i want to close the Window 1 and switch the focus to window 2.

    i tried with below code,but it is throwing nosuchWindowException.

    String parent= driver.getWindowHandle();
    Set x= driver.getWindowHandles();
    Iterator it=x.iterator();

    while(it.hasNext()){
    String child=it.next();
    if(parent.equals(child)){
    System.out.println(driver.switchTo().window(child).getTitle());
    driver.switchTo().window(child);
    driver.close();

    }

    }
    System.out.println(driver.getTitle());

    Hope you help me out.
    thanks.

    1. Hi MUkesh

      String parent= driver.getWindowHandle();
      Set x= driver.getWindowHandles();
      Iterator it=x.iterator();

      while(it.hasNext()){
      String child=it.next();
      if(parent.equals(child)){
      System.out.println(driver.switchTo().window(child).getTitle());

      driver.switchTo().window(parent);
      driver.close();
      driver.switchTo().window(child);
      // Continue your code
      }

      }
      System.out.println(driver.getTitle());

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.