selenium-webdriver Switching Frames To switch to a frame using Java


For an instance, if the html source code of an html view or element is wrapped by an iframe like this:

<iframe src="../images/eightball.gif" name="imgboxName" id="imgboxId">
   <p>iframes example</p>
   <a href="../images/redball.gif" target="imgbox">Red Ball</a>
</iframe><br />

... then to perform any action on the web-elements of the iframe, you have to switch the focus to the iframe first, using any one of the below methods:

Using frame Id (should be used only if you know the id of the iframe).

driver.switchTo().frame("imgboxId"); //imgboxId - Id of the frame

Using frame name (should be used only if you know the name of the iframe).

driver.switchTo().frame("imgboxName"); //imgboxName - Name of the frame

Using frame index (should be used only if you do not have the id or name of the iframe), where the index defines the position of the iframe amongst all frames.

driver.switchTo().frame(0); //0 - Index of the frame

Note: If you have three frames in the page, then the first frame will be at index 0, the second at index 1, and the third at index 2.

Using previously located webelement (should be used only if you have already located the frame and have returned it as a WebElement).

driver.switchTo().frame(frameElement); //frameElement - webelement that is the frame

So, to click on the Red Ball anchor:

driver.findElement(By.linkText("Red Ball")).Click();