`
yidongkaifa
  • 浏览: 4056715 次
文章分类
社区版块
存档分类
最新评论

WebBrowser控件跨域访问页面内容

 
阅读更多

这几天拔测联通的业务系统,可以好好折腾了一阵,这四五天连周末全都加班了,终于搞定了,也总结一下WebBrowser的使用感受。

一开始想省事,就用了System.Windows.Forms.WebBrowser,后来发现问题越来越多,只能不断扩展增加功能,最头疼的就是跨域访问了。

1. 开始使用一网友提示的重载IInternetSecurityManager接口,即重载WebBrowser的方法:
protected override WebBrowserSiteBase CreateWebBrowserSiteBase()
并返回一个实现了IServiceProvider和IInternetSecurityManager接口的对象,然后重载GetSecurityId,为所有站点返回同一个ID,欺骗浏览器。
这种方法开始是可以了,但不总是可以,后来发现页面中出现脚本访问的权限错误,导致有些页面不能正常加载,通过分析javascript脚本确定还是跨域访问的问题,后来把重载的IInternetSecurityManager接口去掉发现还原GetSecurityId之后就可以了,没有脚本错误问题,使用GetSecurityId欺骗浏览器的方法不行了。

2.后来将页面元素访问的接口都使用mshtml命名空间中的IHTMLWindow2、IHTMLDocument2、IHTMLElement、IHTMLElement (for click element)来遍历,但还是会有访问权限的问题,经过大量网上资料查找,后来找到一种方法比较可行,完美解决了跨域访问的问题:

// http://www.codecentrix.com/
// http://codecentrix.blogspot.com/

代码:

using System;
using System.Runtime.InteropServices;
using mshtml;


namespace noock.web
{
public static class CrossFrameIE
{
// Returns null in case of failure.
public static IHTMLDocument2 GetDocumentFromWindow(IHTMLWindow2 htmlWindow)
{
if (htmlWindow == null)
{
return null;
}

// First try the usual way to get the document.
try
{
IHTMLDocument2 doc = htmlWindow.document;
return doc;
}
catch (COMException comEx)
{
// I think COMException won't be ever fired but just to be sure ...
if (comEx.ErrorCode != E_ACCESSDENIED)
{
return null;
}
}
catch (System.UnauthorizedAccessException)
{
}
catch
{
// Any other error.
return null;
}

// At this point the error was E_ACCESSDENIED because the frame contains a document from another domain.
// IE tries to prevent a cross frame scripting security issue.
try
{
// Convert IHTMLWindow2 to IWebBrowser2 using IServiceProvider.
IServiceProvider sp = (IServiceProvider)htmlWindow;

// Use IServiceProvider.QueryService to get IWebBrowser2 object.
Object brws = null;
sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out brws);

// Get the document from IWebBrowser2.
SHDocVw.IWebBrowser2 browser = (SHDocVw.IWebBrowser2)(brws);

return (IHTMLDocument2)browser.Document;
}
catch
{
}

return null;
}

private const int E_ACCESSDENIED = unchecked((int)0x80070005L);
private static Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
private static Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E");
}

// This is the COM IServiceProvider interface, not System.IServiceProvider .Net interface!
[ComImport(), ComVisible(true), Guid("6D5140C1-7436-11CE-8034-00AA006009FA"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IServiceProvider
{
[return: MarshalAs(UnmanagedType.I4)][PreserveSig]
int QueryService(ref Guid guidService, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObject);
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics