Skip to main content

You are here

Switch between two open windows or browser tabs

The following code demonstrates the SwitchTo() function. A popup window is opened from a main window and then control or focus is switched between these windows. This is particularly useful for when a test calls up a second window or popup and testing continues on the newly opened window. This code also demonstrates the use of an "Iterator".

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.BeforeTest;
import org.testng.annotations.Test;

/*-----------------------------------------------------------------------------------
Handle tabs and pop up windows

* Note: Selenium will open each tab as a new window just like pop ups. So the same approach is used.
* 1) Get the window id
* 2) Switch to that window
* 3) You can now find elements etc
*
* This code also demonstrates using the Iterator functionality
------------------------------------------------------------------------------------*/

public class TabbedWindowOperations {
// Define browser variables here to allow it be public for all annotation to access it
WebDriver driver;  
Set<String> windowids = null;
Iterator<String> iter =null;
String popupWindowid= null;
String mainWindowId=null;
String curWindow = null;

@BeforeTest
public void  testSetup() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(6,TimeUnit.SECONDS);
}

@Test
public void popupHandling() throws InterruptedException {
System.out.println("Handling popup window");
driver.get("http://hdfc.com");

windowids = driver.getWindowHandles(); // returns an ID for every opened window
iter = windowids.iterator();  // iterate through open browser and print out their ids. One id only for now.

//String mainWindowId = iter.next();
mainWindowId = driver.getWindowHandle();
System.out.println("Main window handle: "+mainWindowId);

System.out.println("List Window IDs. There should be 1 id now");
System.out.println("=========================================");
while (iter.hasNext()){
//There should be just one item at this point;
System.out.println("Only one ID at this point: "+iter.next());
}


driver.findElement(By.xpath("//*[@id='acc-1-head-2']/a")).click(); // customer care link
driver.findElement(By.xpath("//*[@id='acc-1-section-2']/li[1]/a")).click(); //write to us link
//the above should open a new tab on current browser window BUT Selenium will open it as a new browser window

Thread.sleep(8000L);
windowids = null;
windowids = driver.getWindowHandles(); // returns an ID for every opened window
iter = windowids.iterator();  // iterate through open browser and print out their ids. One id only for now.
System.out.println("List Window IDs. There should be 2 id now");
System.out.println("=========================================");

String[] winList = new String[2];   // create an array to store each window id. Need it for later use
int i=0;
while (iter.hasNext()){
winList[i]=iter.next();
i++;
}

//Print off the window handles. Its a long alphanumeric string
for (int x=0; x<2; x++){
System.out.println("Window Number: " + x + " handle = "+winList[x]);
}

// Now switch between the open window.
for (int yy=0; yy<3; yy++){ // do the switching this number of times

for(int y=0; y<2; y++){ // switch b/w windows 1 and 2
driver.switchTo().window(winList[y]).manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

if(y==0){
curWindow="Main Window";
} else {
curWindow="Popup Window";
}
System.out.println("Switching to " + curWindow + " window... Main window title: "+driver.getTitle());
Thread.sleep(8000L);
}
}
}
}

The following is the C# equivalent of the codes above. I have configured NUnit to run hence the [TestFixture] and [Test] annotations.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;


/*
This tests require NUnit + Selenium reference
*/
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
/*--------------------------------------------------------------*/

{
    [TestFixture]
    class SwitchToExample
    {
        [Test]
        public void SwitchToTest() {
  
            IWebDriver driver;
            ICollection<string> windowids = null;
            IEnumerator<String> iter = null;
        String mainWindowId=null;
        String curWindow = null;

    driver = new FirefoxDriver();
    driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5L));

    Console.WriteLine("Handling popup window");
    driver.Navigate().GoToUrl("http://hdfc.com");

    windowids = driver.WindowHandles; // returns an ID for every opened window
            iter = windowids.GetEnumerator();

            mainWindowId = driver.CurrentWindowHandle;
    Console.WriteLine("Main window handle: "+mainWindowId);

    Console.WriteLine("List Window IDs. There should be 1 id now");
    Console.WriteLine("=========================================");

            for (int i = 0; i < windowids.Count; i++)
            {
                Console.WriteLine(windowids.ElementAt(i));
            }

    driver.FindElement(By.XPath("//*[@id='acc-1-head-2']/a")).Click(); // customer care link
    driver.FindElement(By.XPath("//*[@id='acc-1-section-2']/li[1]/a")).Click(); //write to us link
    //the above should open a new tab on current browser window BUT Selenium will open it as a new browser window

    Thread.Sleep(25);
    windowids = null;
    windowids = driver.WindowHandles; // returns an ID for every opened window
            iter = windowids.GetEnumerator(); ;  // iterate through open browser and print out their ids. One id only for now.
    Console.WriteLine("List Window IDs. There should be 2 id now");
    Console.WriteLine("=========================================");

    for (int i=0; i<windowids.Count;i++){
                 Console.WriteLine(windowids.ElementAt(i));
    }

    // Now switch between the open window.
    for (int yy=0; yy<3; yy++){ // do the switching this number of times

    for(int y=0; y<2; y++){ // switch b/w windows 1 and 2
                    driver.SwitchTo().Window(windowids.ElementAt(y)).Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5L));

    if(y==0){
    curWindow="Main Window";
    } else {
    curWindow="Popup Window";
    }
    Console.WriteLine("Switching to " + curWindow + " window... Main window title: "+driver.Title);
    Thread.Sleep(25);
    }
    }

            driver.Quit();
        }
    }
}

Category: 

Language: 

0
No votes yet

Add new comment

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.

Disclaimer

Note that the codes and ideas expressed on this site are the authors personal views. The content of this website are the personal notes based on the learning experience of the author. The author will not be responsible for any error or damages resulting from you using the content of this website.

Premium Drupal Themes by Adaptivethemes