当我尝试访问此内容时:
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/