selenium, how can I select new window

折月煮酒 提交于 2019-12-03 14:39:32

The window obviously has no name, so you can't select it by name.

  1. If the window is opened via JavaScript and you can change the script, try changing window.open("someUrl"); to window.open("someUrl", "someName");, you'll be then able to select the window by the set name. More information on the MDN doc for window.open().

  2. Selenium RC doesn't support <a href="someUrl" target="_blank"> links (which open the link in a new window). Therefore, if the window is opened by a link of this type, you have to find this <a> element, get the href attribute and call

    selenium.openWindow(theFoundUrl, "theNewWindow");
    selenium.selectWindow("id=theNewWindow");
    
  3. If it is opened via JavaScript before or during the onload event, you'll need to call

    selenium.openWindow("", "theNewWindow");
    selenium.selectWindow("id=theNewWindow");
    

    More information on this in the bug SEL-339 or in the openWindow() and selectWindow() JavaDocs.

  4. If you have only two windows / want to open the newest one, you can try

    selenium.selectPopup()

    That is, obviously, the easiest way, because it selects the first non-top window. Therefore, it's only useful when you want to select the newest popup.

  5. If the new window has a unique title, you can do

    selenium.selectPopup("Title of the window");
    

    or selenium.selectWindow("title=Title of the window");

  6. Otherwise, you must iterate over selenium.getAllWindowNames() to get the right name (Selenium creates names for windows without one). However, you can't hardcode that name into your testcase, because it will change every time, so you'll need to work out some dynamic logic for this.

  7. You won't like this: Go for WebDriver. It should be far more resistant to such problems.

Louise
WebDriver driver = new FirefoxDriver();
WebElement inputhandler = driver.findelement(By.linktext("whatever here"));
inputhandler.click();   
String parentHandle = driver.getWindowHandle();
Set<String> PopHandle = driver.getWindowHandles();
Iterator<String> it = PopHandle.iterator();
String ChildHandle = "";
while(it.hasNext())
{   
    if (it.next() != parentHandle)
    {   
        ChildHandle = it.next().toString();
        // because the new window will be the last one opened
    }
}
driver.switchTo().window(ChildHandle);
WebDriverWait wait1 = new WebDriverWait(driver,30);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.id("something on page")));

// do whatever you want to do in the page here

driver.close();
driver.switchTo().window(parentHandle);

You might not be using the correct window ID.

Check out this link. You might find your answer here.

Let me know you this helps.

Try selenium.getAllWindowNames(), selenium.getAllWindowTitles()..one of them will work for sure.

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