Developers can also embed external documents or documents from another domain using the <iframe>
tag, also known as inline frames. Various social media websites provide buttons that can be embedded in your web applications to link to these websites. For example, you can add a Twitter-follow button in your application, as follows:
<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/follow_button.html?screen_name=upgundecha" style="width:300px; height:20px;"></iframe>
Identifying and working with the <iframe>
tag is similar to a frame that is created with the <frameset>
tag. In this recipe, we will identify the <iframe>
tag that is nested in another frame.
We will create a test on a sample page which embeds the <iframe>
tag within a frame. We will move to the parent frame first and then to the <iframe>
tag. The test will click the element within the <iframe>
tag and operate on a pop-up window currently displayed. Finally, it will switch back to the main document. This is implemented as shown in the following code example:
@Test public void testIFrame() { // Store the handle of current driver window String currentWindow = driver.getWindowHandle(); // The frame on the right side has a nested iframe containing 'Twitter // Follow' Button // Activate the frame on right side using it's name attribute try { driver.switchTo().frame("right"); // Get the iframe element WebElement twitterFrame = driver.findElement(By.tagName("iframe")); try { // Activate the iframe driver.switchTo().frame(twitterFrame); // Get and Click the follow button from iframe // a Popup Window will appear after click WebElement button = driver.findElement(By.id("follow-button")); button.click(); try { // The Twitter Popup does not have name or title. // Script will get handles of all open windows and // desired window will be activated by checking it's Title for (String windowId : driver.getWindowHandles()) { driver.switchTo().window(windowId); if (driver.getTitle().equals( "Unmesh Gundecha (@upgundecha) on Twitter")) { assertTrue("Twitter Login Popup Window Found", true); driver.close(); break; } } } finally { // Switch back to original driver window driver.switchTo().window(currentWindow); } } finally { // switch back to Page from the frame driver.switchTo().defaultContent(); } } finally { // switch back to Page from the frame driver.switchTo().defaultContent(); } }
Working with IFRAME or inline frame is similar to working with a normal frame. In this example, the <iframe>
element is located using the findElement()
method by passing the tag:
WebElement twitterFrame = driver.findElement(By.tagName("iframe"));
To activate the frame, the driver.switchTo().frame()
method is called by passing it an instance of the WebElement
, as follows:
driver.switchTo().frame(twitterFrame)
3.12.76.164