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.
///
///
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(); } }
///
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.
