最近做项目遇到了webbrowser,对于如何获取和设置页面内容作了些研究,下面是自己整理的一些资料,希望可以帮助更多的人。

  1.获取页面js和调用js函数

首先是测试页面,

<html>
<head>
<title>demo</title>
<script language="JavaScript" type="text/javascript">
var testText = "Zswang";
function ShowMessage(AText)
{
    alert(testText);
    alert(AText);
}
</script>
</head>

下面是读取页面js和调用js函数的方法:

//项目中添加Micrsoft.mshtml引用
using
mshtml; using System.Reflection; private void button1_Click(object sender, EventArgs e) { IHTMLDocument2 vDocument = webBrowser1.Document.DomDocument as IHTMLDocument2; IHTMLWindow2 vWindow = (IHTMLWindow2)vDocument.parentWindow; Type vWindowType = vWindow.GetType(); object testText = vWindowType.InvokeMember("testText", BindingFlags.GetProperty, null, vWindow, new object[] { }); // 读取 Console.WriteLine(testText); vWindowType.InvokeMember("testText", BindingFlags.SetProperty, null, vWindow, new object[] { "Zswang 路过" }); // 设置 vWindowType.InvokeMember("ShowMessage", BindingFlags.InvokeMethod, null, vWindow, new object[] { 12345 }); // 执行方法 } private void button2_Click(object sender, EventArgs e) { IHTMLDocument2 vDocument = webBrowser1.Document.DomDocument as IHTMLDocument2; IHTMLWindow2 vWindow = (IHTMLWindow2)vDocument.parentWindow; vWindow.execScript("ShowMessage(67890);", "JavaScript"); // 执行脚本 }
如果页面中嵌入了iFrame或者Frame,名称为mainFrame,则上边的第一句应该写为
IHTMLDocument2 vDocument = webBrowser1.Document.Window.Frames["mainFrame"].Document.DomDocument as IHTMLDocument2;
2、根据元素的id检索页面中的元素
//获取id为input0的元素
HtmlElement he=this.webBrowser1.Document.GetElementById("input0");
he.InnerText="这是我写的内容";
//同样对于有页面中嵌入了iFrame或者Frame
HtmlElement he=this.webBrowser1.Document.Window.Frames["mainFrame"].Document.GetElementById("input0");

 

 
 
 

相关文章:

  • 2021-09-20
  • 2021-06-26
  • 2021-09-24
  • 2022-12-23
  • 2021-07-10
  • 2022-12-23
  • 2021-09-09
  • 2021-08-01
猜你喜欢
  • 2022-12-23
  • 2021-11-01
  • 2021-08-08
  • 2021-11-01
相关资源
相似解决方案