How to switch between two windows in browser using Selenium java

前端 未结 8 1155
面向向阳花
面向向阳花 2020-12-11 06:57

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\'

相关标签:
8条回答
  • 2020-12-11 07:55

    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();
    
    0 讨论(0)
  • 2020-12-11 07:55
        // fetch all windows before clicking on new window link.
        Set<String> windowHandles = driver.getWindowHandles();
        // Click on link to open new window
        driver.findElement(By.tagName("a")).click();  // link to open new window
    
        Set<String> updatedWindowHandles = driver.getWindowHandles();
        updatedWindowHandles.removeAll(windowHandles);
        for (String window: updatedWindowHandles) {
            driver.switchTo().window(window);
        }
    
    0 讨论(0)
提交回复
热议问题