Search On Google

Tuesday, February 19, 2019

Selenium multiple window handling

How to handle multiple window in browser with selenium?

For handling multiple window you have to follow some rules as given below.

String MainWindow=driver.getWindowHandle(); //gives parent window ID only

Set allwindowList = driver.getWindowHandles() //gives a set of windows ID

You should check ID with parent ID by looping over ID and do work as you wish at any page you want.

How to switch window:-
driver.switchTo().window(handle);
For switching window in selenium we use above code.

Program for switching and doing some tast on different window in selenium:-

"package pkg1;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class MyClass913_multiple_window_handling { 
    public static void main(String[] args) {       
   
        System.setProperty(""webdriver.chrome.driver"",""C:\\Users\\Desk-105\\Documents\\SELENIUM\\chromedriver.exe"");   
        WebDriver driver = new ChromeDriver();   

        /**
     * Open multiple windows.
   */
     
         String pageUrl = ""http://www.google.com"";
   driver.get(pageUrl);
    JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
    String jsOpenNewWindow = ""window.open('""+pageUrl+""');"";

    for(int i=0;i<6;i++)
    {
     jsExecutor.executeScript(jsOpenNewWindow);
     try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
     System.out.println((i+1)+"" opennd."");
    }
     
 
 
    /**
     * Handle multiple windows.
     */
         String MainWindow=driver.getWindowHandle();
         System.out.println(MainWindow);
         for( String window : driver.getWindowHandles()){
          System.out.println(window);
         }
       
         /**
          * window switching and closing new tabs
          */
         for(String handle : driver.getWindowHandles()) {
             if (!handle.equals(MainWindow)) {
              try {
      Thread.sleep(1000);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
                 driver.switchTo().window(handle);
                 driver.close();
             }
         }

       
     
    }
}
"

No comments:

Post a Comment

About Me

My photo
Mumbai, Maharashtra, India