c# - WebBrowser IFrame 访问导致未经授权的访问?

标签 c# winforms

当我尝试访问此内容时:

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 });
}

关于c# - WebBrowser IFrame 访问导致未经授权的访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20013498/

相关文章:

c# - Parentform 和 Owner 有什么区别

c# - 在 C# 2.0(Windows 窗体)中使用注册表

c# - 接管别人的代码

c# - 使用 XSL 将 XML 转换为 XAML

c# - 序列化程序未使用 100% CPU

c# - 如何通过t4生成自定义类?

c# - 在另一个已经打开的窗体上执行函数

c# - 切换内部循环影响性能?

c# - "Contains"未从我的文本文件中读取 C#

c# - 如何使用现有的 ToolStripRenderer 绘制托管的 NumericUpDown?