Working with IFrame elements and Selenium 2+ in C#

I added a lengthy answer to the StackOverflow question on switching focus to an iFrame when using Selenium to automate a UI for testing and thought it deserved a blog post.

First you need to select the iFrame and switch the driver context to it. The iFrame I’m working against doesn’t have an id, and there will only be one on this particular page.

This is an example of using it straight out of the box. I have access to the driver through a static property. I set this when I first told Selenium what type of browser I wanted to use. (example Driver = new FirefoxDriver();)

try { var iFrameElement = Driver.FindElementByTagName("iFrame"); var driver = Driver.SwitchTo().Frame(this.iFrameElement);
var element = driver.FindElement(selector);

// do what you need with the element

} finally { // don't forget to switch back to the DefaultContent Driver.SwitchTo().DefaultContent(); }

Note: You have to get the information from the IWebElement .Text or .Click for example, before calling Driver.SwitchTo().DefaultContent();

Then I created some extension methods to make this easier to call.

///

/// Switch to the IFrame and get the new driver. /// Call SwitchOutofIFrame after done working with the element. /// /// the current driver /// the IFrame driver. public static IWebDriver SwitchToIFrame(this RemoteWebDriver driver) { // http://computerrecipes.wordpress.com/2012/08/23/selenium-webdriver-interact-with-an-element-inside-an-iframe/ // http://stackoverflow.com/questions/3549584/selenium-2-switching-focus-to-a-frame-that-has-no-name-id var iFrameElement = driver.FindElementByTagName("iFrame"); return driver.SwitchTo().Frame(iFrameElement); }

///

/// Switch back to the default content. /// /// the current driver public static void SwitchOutOfIFrame(this IWebDriver driver) { driver.SwitchTo().DefaultContent(); }

public static void ClickIFrameElement(this RemoteWebDriver driver, By selector) { var iFrameDriver = driver.SwitchToIFrame(); try { iFrameDriver.GetAndWaitForElement(selector).Clik(); } finally { driver.SwitchOutOfIFrame(); } }

public static string GetTextFromIFrameElement(this RemoteWebDriver driver, By selector) { var iFrameDriver = driver.SwitchToIFrame(); try { return iFrameDriver.GetAndWaitForElement(selector).Text; } finally { driver.SwitchOutOfIFrame(); } }

///

/// Use the WebDriverWait to find an element. If it doesn't find it after before the timeout an exception is thrown. /// /// The current driver Browser.Driver. /// how to find the element /// if the element isn't found after the timeout /// IWebElement public static IWebElement GetAndWaitForElement(this IWebDriver driver, By bySelector) { try { // give more time on the agents var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(ProcessBase.IsRunningOnTestAgent ? 15 : 5)); return wait.Until(ExpectedConditions.ElementIsVisible(bySelector)); } catch (Exception e) { // breakpoint here to retry for debugging. Trace.WriteLine(e.Message + " Selector: " + bySelector); throw; } }

And this is what my Page.cs that represents a web page can look like with the extension methods:

public string GetTitle() { return Browser.Driver.GetTextFromIFrameElement(By.Id("pageTitle")); }

public void ClickPrintButton() { Browser.Driver.ClickIFrameElement(By.Id("printButton")); }

The limitation with the extension methods is that they limit what you can get out of the element, before it switches back the default content. When more is needed, use the first plain vanilla call to switchTo or a combination of the extension methods inline.

This article is part of the GWB Archives. Original Author: Aligned

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.