Does WebBrowser IFrame access cause unauthorized access?

When I try to access it:

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

I get an unauthorized access exception. What's happening!? I can view the entire document in Object Explorer while an exception is thrown, I can also manually click this iframe inside my webBrowser1, but when I try to access it inside my application, do I get an error? What kind of magic is this?

+1
source share
1 answer

This is because the browser will not allow you to access iframes from another domain, this also happens on https sites where the domain name is the same, fortunately there is a way around this.

IFrame JS .

URL- iframe:

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

, URL- iframe, url, , , , eval javascript , 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 });
}
+1

All Articles