Switch Frames

What is a frame

To get a straight-forward feeling of what a frame is:

Figure xx: Frames(Source code vs. Actual Page)

Frame has a lot of built-in defects regarding web design and has deprecated in HTML5.

What is a iframe

An iFrame (‘i’ doe ‘inline’) is an HTML document embedded inside the current HTML document on a website. iFrame HTML element is used to insert content from another source, such as an advertisement, into a Web page. A Web designer can change an iFrame’s content without making them reload the complete website.

A website can have multiple frames on a single page, and iframes can be nested.

Figure 3.x: iFrame Source Code

How many frames we have on this page?

We can take a look at the page source code to find that out, or we can find that out using WebDriver:

List iframes = driver.findElements(By.tagName(“iframe”));
System.out.println(“iframe count: ” + iframes.size());

Switch Frames

Webdriver will not be able to access the elements in that frame until you switch driver to that frame. Frame can be identified via a index number, an ID or a Name. These are thus the 3 type of arguments that WebDriver’s driver.switchTo().frame() method takes:

A number.
Select a frame by its (zero-based) index. That is, if a page has three frames, the first frame would be at index 0, the second at index 1 and the third at index 2. Once the frame has been selected, all subsequent calls on the WebDriver interface are made to that frame.

A name or ID.
Select a frame by its name or ID. Frames located by matching name attributes are always given precedence over those matched by ID.

A previously found WebElement.
Select a frame using its previously located WebElement.
Get the frame by it’s id/name or locate it by driver.findElement() and you’ll be good.

Switch back to main page

driver.switchTo().defaultContent();

Switch back to parent frame for nested frames

driver.switchTo().parentFrame();