Unable to get new window handle with Selenium WebDriver in Java on IE

后端 未结 2 1171
执笔经年
执笔经年 2021-01-26 06:57

When I click a button on a page (in IE browser), a new popup page opens. My attempts to get the window handle for this popup have failed. Here is my first attempt:



        
2条回答
  •  迷失自我
    2021-01-26 07:52

    There are 2 things you need to do:

    1. Change the security setting in IE browser:

      Open IE browser, click on "Internet Options" => "Security" => tick "Enable Protected Mode" for "Internet", "Local intranet", "Trusted sites" and "Restricted sites".

      This gives IE driver the capability to get control of the new window handle, so that when you call driver.getWindowHandles(); or driver.getWindowHandles().size(); you will get all the handles including the original window and the new windows. To be more accurate, you just need to set the security setting for all 4 domains to be the same which means you can uncheck "Enable Protected Mode" for all 4 domains but it is discouraged obviously.

    2. After you call driver.switchTo().window(windowName);, you need to add ((JavascriptExecutor) driver).executeScript("window.focus();"); before the IE driver can perform any actions on the window.

      This is because IE driver needs the window that it is working on to be at the foreground, this line helps the driver get the focus of the window so that it can perform any actions on window that you want.

    The following is a complete sample:

        String baseWin = driver.getWindowHandle();
        //Some methods to open new window, e.g.
        driver.findElementBy("home-button").click();
    
        //loop through all open windows to find out the new window
        for(String winHandle : driver.getWindowHandles()){
            if(!winHandle.equals(baseWin)){
                driver.switchTo().window(winHandle);
                //your actions with the new window, e.g.
                String newURL = driver.getCurrentUrl();
            }
        }
    
        //switch back to the main window after your actions with the new window
        driver.close();
        driver.switchTo().window(baseWin);
    
        //let the driver focus on the base window again to continue your testing
        ((JavascriptExecutor) driver).executeScript("window.focus();");
    

提交回复
热议问题