文档详情

使用C#处理WebBrowser控件在不同域名中的跨域问题.doc

发布:2016-12-30约字共8页下载文档
文本预览下载声明
使用C#处理WebBrowser控件在不同域名中的跨域问题 们在做web测试时,经常会使用WebBrowser来进行一些自动化的任务而有些网页上面会用IFrame去嵌套别的页面,这些页面可能不是在相同域名下的,这时就会出现跨域问题,无法直接在WebBrowser中获取到IFrame中的元素,接下来介绍如何解决此问题,需要了解的朋友可以参考下 我们在做web测试时,经常会使用WebBrowser来进行一些自动化的任务。而有些网页上面会用IFrame去嵌套别的页面,这些页面可能不是在相同域名下的,这时就会出现跨域问题,无法直接在WebBrowser中获取到IFrame中的元素。下面来做个试验,自己写个页面嵌套一个百度的首页,然后在我们自己的页面上输入要查询的词,最后在百度上自动完成搜索。 复制代码 代码如下: !DOCTYPE html html lang=en xmlns=/1999/xhtml head meta charset=utf-8 / title/title /head body iframe id=baidu style=float:left; width=500 height=500 src=/iframe div 测试值:input id=search type=text / /div /body /html 下面再建一个简单的WinForm工程测试一下,界面如下: 下面就是WebBrowser的测试代码: 复制代码 代码如下: using System; using System.Windows.Forms; namespace WebBrowserTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.webBrowser1.Navigate(this.textBox1.Text); } private void button2_Click(object sender, EventArgs e) { var doc = this.webBrowser1.Document; var frames = doc.Window.Frames; String testValue = doc.GetElementById(search).GetAttribute(value); frames[0].Document.GetElementById(kw).SetAttribute(value, testValue); frames[0].Document.GetElementById(su).InvokeMember(click); } } } 我们运行我们的测试程序后,加载之前我们自己写的页面后,在自己的页面上输入我们要查询的词,点击测试按钮,就会看到程序报未处理 UnauthorizedAccessException错误: 下面来编写一个Helper类来解决这个问题,主要原理大致就是利用IWebBrowser2这个接口来获取Ifream中的Dom,IWebBrowser2中的document可以转换为IHtmlDocument1,IHtmlDocument2,IHtmlDocument3。 复制代码 代码如下: using System; using System.Runtime.InteropServices; using System.Windows.Forms; using mshtml; namespace WebBrowserTest { // 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
显示全部
相似文档