In Selenium WebDriver, in order to handle or work with the child browser the first step you need to do is switch control of the browser from the parent window to the child window. At present the control will be on the current window so to perform any operation on the child window you need to use the following command to switch control of the browser to the child window :
In this command, window method takes an argument of type string which means we have to pass the unique id of the browser that is opened by web Driver.
In order to get current browser unique id we use getWindowHandle() method.
In order to get unique ids of all the browsers that is opened by web driver we use getWindowHandles() method which returns set<String>. Store all the unique ids in a set, use the traversing concept to retrieve the unique id one at a time.
For the first time when next() method is used, we’ll get the first unique id of the browser that is opened by web driver for the first time(i.e; parent window address/unique id).
To give a better explanation for this type of pop up, here is an example. Follow the steps given below :
1) Launch Eclipse, create package, and then create a class named “test1.java”.
2) Navigate to the site “http://www.yatra.com/”.
3) Click on the “Login With Facebook” option which is given on the upper right side of the page. For clicking on it, first you need to locate it. Once you get the selector add these lines of code :
WebDriver driver=new FirefoxDriver();
Once the option “Login With Facebook” is clicked, another web page will be displayed where you have to again click on “Login With Facebook” option.
4) As soon as you click on Login with Facebook option, a pop up will appear. From here onward if you will try to perform any operation on the web elements present on the pop up window, you can not do directly. You need to switch the browser’s control from the current window to this pop up window. Every page has a unique id, to get these ids we will use getWindowHandle() method. To get the unique ids of all the windows which the browser opens up, we use getWindowHandles() method. Add the following lines of code to your script :
Set <String> set1=driver.getWindowHandles();
Iterator <String> win1=set1.iterator();
5) Now we have successfully switched on the child window. Now enter some random username and password, and click on Submit button. It will show an error message saying invalid username and password. Now you have to come back to the parent window and we have to click on “Sign Up”.
That’s all in handling the child browser pop up window…!!!