MattJ
MattJ

Reputation: 329

C# Selenium Webdriver Find Element Within Iframe

I am having trouble finding an iframe. I want to switch to this iframe then click on an element within it.

I have tried finding the iframe using Id, Xpath, TagName, and CssSelector but my test times out while looking for the element each time.

This is the iframe as it appears in the page source:

<div xmlns="http://www.w3.org/1999/xhtml" id="dashboardView" style="display: block;">
        <iframe id="dashboardViewFrame" border="0" scrolling="no" frameborder="0"
style="visibility: visible; height: 607px; width: 1280px; background-color: transparent;"
src="HtmlViewer.ashx?Dd_ContentId=6a8a44ae-2bd5-4f3c-8583-e777279ad4f2"></iframe>
    </div>

<iframe xmlns="http://www.w3.org/1999/xhtml" id="dashboardViewFrame" border="0" scrolling="no"
frameborder="0" style="visibility: visible; height: 607px; width: 1280px; background-color:
transparent;" src="HtmlViewer.ashx?Dd_ContentId=6a8a44ae-2bd5-4f3c-8583-e777279ad4f2"></iframe>

Here is my current code:

    public static bool IsAt
    {
        get
        {
            try
            {
                var dashboardiFrame = Driver.Instance.FindElement(By.Id("dashboardViewFrame"));
                //todo switch to iframe
                //todo find element within iframe
                return true;
            }
            catch
            {
                return false;
            }
        }
    }

Can someone please suggest a way to find the iframe and switch to it?

Upvotes: 5

Views: 9386

Answers (2)

ahmed Bahgat
ahmed Bahgat

Reputation: 61

some times you have to sleep around 5 second till page load completely then find frame.

try this

thread.sleep(50000); IwebElement Frame = Driver.SwitchTo().Frame("id of the frame");

//then any element inside frame should get by this line

Frame.FindElement(By.id("ID of element inside frame");

Upvotes: 6

MattJ
MattJ

Reputation: 329

The main problem was that my test opened a new window, but my test was looking for elements on the old window. I resolved that by switching to the new page using:

Driver.Instance.SwitchTo().Window(Driver.Instance.WindowHandles.Last());

Then I could switch to the iframe also by also using SwitchTo() as shown below:

public static bool IsAt
    {
        get
        {
            try
            {
                Driver.Instance.SwitchTo().Window(Driver.Instance.WindowHandles.Last());
                var DBViFrame = Driver.Instance.FindElement(By.Id("dashboardViewFrame"));
                Driver.Instance.SwitchTo().Frame(DBViFrame);
                var dataEntryButton = Driver.Instance.FindElement(By.Id("HyperlinkDataEntry"));
                dataEntryButton.Click();
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
    }

Upvotes: 3

Related Questions