网络浏览器 IFrame 访问导致未经授权的访问



当我尝试访问它时:

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

我收到未经授权的访问异常。这是怎么回事!?我可以在抛出异常时在对象浏览器中查看整个文档,我也可以在我的 webBrowser1 中手动单击此 iframe,但是当我尝试在我的应用程序中访问它时,我收到错误?这是什么魔法?

这是因为浏览器不允许您从另一个域访问 iframe,域名相同的 https 站点也会发生这种情况,幸运的是有一种方法可以解决这个问题。

页面完全加载后,可以使用 JS 获取 IFrame 的内容。

首先加载嵌入了 iframe 的页面的 url:

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

然后在文档完成事件中,检查 iframe url 是否已加载,而不是我们导航到的原始 url,加载后,使用 javascript 中的 eval 函数运行我们自己的代码来拉取 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 });
}

最新更新