ojek
ojek

Reputation: 10068

WebBrowser IFrame access causing unauthorized access?

When I try to access this:

var anchors = webBrowser1.Document.Window.Frames[0].Document.GetElementsByTagName("a");

I get the unauthorized access exception. What is going on!? I can look through the whole document in object browser while exception is being thrown, I can also manually click through this iframe inside my webBrowser1, but when I try to access it inside of my app, I get error? What wizardy is this?

Upvotes: 2

Views: 4968

Answers (1)

David Thompson
David Thompson

Reputation: 2922

This is because the browser wont allow you to access iframes from another domain, this also occurs with https sites where the domain name is the same, fortunately there is a way around this.

You can get the content of an IFrame by using JS once the page has fully loaded.

First load the url of the page that has an iframe embedded:

webBrowser1.Navigate("https://www.example.com/pagecontaingiframe.html");
webBrowser1.DocumentCompleted += WebBrowserDocumentCompleted;

Then in the document completed event, check that the iframe url has loaded, not the original url we navigated to, once we have loaded that, use the eval function in javascript to run our own code to pull the content of the iframe.

void WebBrowserDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    // Optionally check that the url is the original document
    // search for an iframe and its url here first.
    // Then store the name and url for the next step


    // And the magic begins
    if (e.Url.AbsolutePath != new Uri("https://www.example.com/iframeyouneedurl.html").AbsolutePath)
        return;

    webBrowser1.DocumentCompleted -= WebBrowserDocumentCompleted;

    string jCode = "var iframe = document.getElementsByName('iframe_element')[0]; var innerDoc = iframe.contentDocument || iframe.contentWindow.document; innerDoc.documentElement.innerHTML";
    string html = webBrowser1.Document.InvokeScript("eval", new object[] { jCode });
}

Upvotes: 3

Related Questions