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

谁说胖子不能爱 提交于 2019-12-02 11:37:14

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();");

please note Pop Up is not a new window its an Iframe treat it as IFrame driver.getWindowHandles(); is for handling multiple tabs in browser its not for handling Iframe

you should use driver.switchTo().frame() to switch into that pop up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!