Handling multiple browser windows/popups using selenium

There are situations in which we get browser popups or multiple browser window opens, when we open an URL or click on an element on browser.

popups can be blocked in browser using some browser addons,
but for testing purpose, sometimes we need to allow the popups or multiple windows.

A single instance of selenium web-driver can handle multiple popups and browser windows.
Let's see how web-driver handles these above mentioned popups or browser windows.

Selenium provides 2 methods getWindowHandle() and getWindowHandles() to deal with the multiple browser windows.


getWindowHandle() - this method returns the current browser window handle id that the web-driver is currently holding.

getWindowHandles() - this method returns set of browser window handle ids that are invoked/opened by the web-driver.

and we use switchTo().window(window_handle_id) to switch to different browser windows of the web-driver.

Below is the code implementation and comments of each line explanation

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class WindowHandling {

public static void main(String[] args) throws InterruptedException {
   WebDriver d=new FirefoxDriver();
   d.manage().timeouts().implicitlyWait(10L, TimeUnit.SECONDS);
   d.get("http://www.popuptest.com/popuptest2.html");
 
   Set s=d.getWindowHandles(); //s holds the set of all browser windows
   Iterator iter=s.iterator();
   String maintab=(String) iter.next();//maintab holds the 1st browser window
   String childtab=(String) iter.next();//childtab holds the next browser window

   d.switchTo().window(childtab); //move to child browser window
   System.out.println(childtab + d.getTitle());
        d.close();
   d.switchTo().window(maintab); //move to parent browser window
   System.out.println(maintab+d.getTitle());
        d.close();
   //if a driver opens more than one browser windows, then we can loop to 
   //move each of the window and perform some actions
   /*while(iter.hasNext())
    {
        System.out.println(iter.next());
    }*/
   }
}

No comments:

Post a Comment