This is my implementation of switching to a frame for all browsers, because switching to a frame by ID or name does not work for Chrome (with the latest versions)
- using Xpath (more elegant / readable code):
/** * This switch to frame method improves standard way to switching to frame * ( driver.switchTo().{@linkplain org.openqa.selenium.WebDriver.TargetLocator#frame(String) frame(String nameOrId)} ) * because Chrome browser has problem with this method. <br/> * * Bug: http://code.google.com/p/chromedriver/issues/detail?id=107 * @param frameIdOrName the id or name of the <frame> or <iframe> element * @return This driver focused on the given frame. */ public WebDriver switchToFrameByIdOrName(String frameNameOrId) { if (driver instanceof ChromeDriver) { String frameElementXpath = String.format("//frame[@name='%1$s' or @id='%1$s']", frameNameOrId); WebElement f = driver.findElement(By.xpath(frameElementXpath)); return driver.switchTo().frame(f); } return driver.switchTo().frame(frameNameOrId); }
or
- using CSS selectors (because the CSS selector should be a faster way to find elements. For more information, see Choosing WebDriver Locators :
public WebDriver switchToFrameByIdOrName(String frameIdOrName) { if (!(driver instanceof ChromeDriver)) { return driver.switchTo().frame(frameIdOrName); } WebElement frame = null; try { frame = driver.findElement(By.cssSelector("frame[id='" + frameIdOrName + "']")); } catch (NoSuchElementException e) { /* It ok for the moment */ } if (frame == null) { try { frame = driver.findElement(By.cssSelector("frame[name='" + frameIdOrName + "']")); } catch (NoSuchElementException e) { log.severe(String.format("CORE > switchToFrameByIdOrName() error: Frame with name or id '%s' not found.", frameIdOrName)); } } return driver.switchTo().frame(element); }
I use:
Selenium 2.37.1 Session info: chrome=31.0.1650.57) Driver info: chromedriver=2.7.236900,platform=Windows NT 6.1 SP1 x86_64
Danix source share