How to switch between two windows in browser using Selenium java

78,936

Solution 1

To switch between windows we have method.

driver.switchTo().window("window name") 

To get the different windows handle, we have method.

driver.getWindowHandles()

Example:

    File file = new File("G:\\Selenium\\All_Jars\\chromedriver.exe");
    System.setProperty("webdriver.chrome.driver",file.getAbsolutePath() );
    driver = new ChromeDriver();

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

    driver.get("http://www.rediff.com/");

    //Get all window handles
    Set<String> allHandles = driver.getWindowHandles();

    //count the handles Here count is=2
    System.out.println("Count of windows:"+allHandles.size());      

    //Get current handle or default handle
    String currentWindowHandle = allHandles.iterator().next();
    System.out.println("currentWindow Handle"+currentWindowHandle);

    //Remove first/default Handle
    allHandles.remove(allHandles.iterator().next());

    //get the last Window Handle
    String lastHandle = allHandles.iterator().next();
    System.out.println("last window handle"+lastHandle);

    //switch to second/last window, because we know there are only two windows 1-parent window 2-other window(ad window)
driver.switchTo().window(lastHandle);
    System.out.println(driver.getTitle());
    driver.findElement(By.tagName("body")).click();

Solution 2

I finally found the answer, I used the below method to switch to the new window,

public String switchwindow(String object, String data){
        try {

        String winHandleBefore = driver.getWindowHandle();

        for(String winHandle : driver.getWindowHandles()){
            driver.switchTo().window(winHandle);
        }
        }catch(Exception e){
        return Constants.KEYWORD_FAIL+ "Unable to Switch Window" + e.getMessage();
        }
        return Constants.KEYWORD_PASS;
        }

To move to parent window, i used the following code,

 public String switchwindowback(String object, String data){
            try {
                String winHandleBefore = driver.getWindowHandle();
                driver.close(); 
                //Switch back to original browser (first window)
                driver.switchTo().window(winHandleBefore);
                //continue with original browser (first window)
            }catch(Exception e){
            return Constants.KEYWORD_FAIL+ "Unable to Switch to main window" + e.getMessage();
            }
            return Constants.KEYWORD_PASS;
            }

Solution 3

Yes this is possible. First you need to save the refrence to current window.

String parentWindow= driver.getWindowHandle();

The after having clicked the link, you need to switch to the other window.

List<String> allWindows = driver.getWindowHandles();
for(String curWindow : allWindows){
    driver.switchTo().window(curWindow);
}

This is where you perform operations on new window, finally closing it with

driver.close();

and switch back to parent window

driver.switchTo().window(parentWindow);

Solution 4

In an excerpt from a getting started with selenium webdriver project on github,

    /**
     * Waits for a window to appear, then switches to it.
     * @param regex Regex enabled. Url of the window, or title.
     * @return
     */
    public AutomationTest waitForWindow(String regex) {
        Set<String> windows = driver.getWindowHandles();

        for (String window : windows) {
            try {
                driver.switchTo().window(window);

                p = Pattern.compile(regex);
                m = p.matcher(driver.getCurrentUrl());

                if (m.find()) {
                    attempts = 0;
                    return switchToWindow(regex);
                }
                else {
                    // try for title
                    m = p.matcher(driver.getTitle());

                    if (m.find()) {
                        attempts = 0;
                        return switchToWindow(regex);
                    }
                }
            } catch(NoSuchWindowException e) {
                if (attempts <= MAX_ATTEMPTS) {
                    attempts++;

                    try {Thread.sleep(1);}catch(Exception x) { x.printStackTrace(); }

                    return waitForWindow(regex);
                } else {
                    fail("Window with url|title: " + regex + " did not appear after " + MAX_ATTEMPTS + " tries. Exiting.");
                }
            }
        }

        // when we reach this point, that means no window exists with that title..
        if (attempts == MAX_ATTEMPTS) {
            fail("Window with title: " + regex + " did not appear after 5 tries. Exiting.");
            return this;
        } else {
            System.out.println("#waitForWindow() : Window doesn't exist yet. [" + regex + "] Trying again. " + attempts + "/" + MAX_ATTEMPTS);
            attempts++;
            return waitForWindow(regex);
        }
    }

    /**
     * Switch's to a window that is already in existance.
     * @param regex Regex enabled. Url of the window, or title.
     * @return
     */
    public AutomationTest switchToWindow(String regex) {
        Set<String> windows = driver.getWindowHandles();

        for (String window : windows) {
            driver.switchTo().window(window);
            System.out.println(String.format("#switchToWindow() : title=%s ; url=%s",
                    driver.getTitle(),
                    driver.getCurrentUrl()));

            p = Pattern.compile(regex);
            m = p.matcher(driver.getTitle());

            if (m.find()) return this;
            else {
                m = p.matcher(driver.getCurrentUrl());
                if (m.find()) return this;
            }
        }

        fail("Could not switch to window with title / url: " + regex);
        return this;
    }

These are 2 custom functions to help you get started. Or you can check out that project from github to make your selenium projects better designed and easier.

These functions can switch to, or wait for (if it doesn't exist) a window with a certain title / url.

Share:
78,936
Prasanna
Author by

Prasanna

Updated on July 09, 2022

Comments

  • Prasanna
    Prasanna almost 2 years

    I'm working with Selenium Automation. In this, When i click a link in a current window, a new window opens. I just want to switch the control to the new window. But i can't do this.Actually the new window is an auto-generated one. That is, link will be generated dynamically. Help me friends...

  • ddavison
    ddavison over 10 years
    make sure that you change the "AutomationTest" variable's to void. This method is proven, and works. It's on your side that it is not working. If you'd like a working copy, then download the project that this is from and import it into eclipse to see.
  • SpartanElite
    SpartanElite over 10 years
    Which part is not working. Showing some of your code will help us help you better. After you switch to the new windows handle, all operations will be performed on that window. It should work.
  • ddavison
    ddavison over 10 years
    it's in the SampleFunctionalTest class under src/tests/java. it starts at line 57
  • aimbire
    aimbire over 10 years
    I remember having this problem and asking on #selenium in the IRC. What's intresting to try out was something pointed out to me. I edited the code so it can make clear, but you must guarantee while looping through the window handles that you are not actually switching to the current one.
  • Prasanna
    Prasanna over 10 years
    Finally it works sir. I have used some code that i mentioned in my answer. Kindly have a look into it and give me your feedback sir. Thanks..!!
  • Prasanna
    Prasanna over 10 years
    Finally it works sir. I have used some code that i mentioned in my answer. Kindly have a look into it and give me your feedback sir. Thanks..!! @SpartanElite
  • ndtreviv
    ndtreviv almost 8 years
    I would recommend only switching to the window if it's not the current window. ie: Compare withHandleBefore with withHandle. Otherwise you're switching through all the windows unnecessarily.