WebBrowser IFrame 访问导致未经授权的访问? [英] WebBrowser IFrame access causing unauthorized access?

查看:38
本文介绍了WebBrowser IFrame 访问导致未经授权的访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试访问它时:

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

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

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?

推荐答案

这是因为浏览器不允许你从另一个域访问 iframe,这在域名相同的 https 站点也会发生,幸好有解决这个问题.

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.

您可以在页面完全加载后使用 JS 获取 IFrame 的内容.

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

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

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

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

然后在文档完成事件中,检查 iframe url 是否已加载,而不是我们导航到的原始 url,加载后,使用 javascript 中的 eval 函数运行我们自己的代码拉取 iframe 的内容.

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

这篇关于WebBrowser IFrame 访问导致未经授权的访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆