zoukankan      html  css  js  c++  java
  • C# webbrowser获取和改变内置网页内容

      最近做项目遇到了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");
    
    
    
     
     
     
  • 相关阅读:
    博客园随笔备份Java脚本
    vue 获取 referer
    EntityFramework的天坑
    清空stringbuilder
    相关的验证的正则表达式
    清空StringBuilder的三种方法及效率
    oracle中的字符串函数详解
    浅谈C# application.DoEvent作用
    C# 简单Tcp通信demo
    C#中http请求下载的常用方式demo
  • 原文地址:https://www.cnblogs.com/saotao/p/2745252.html
Copyright © 2011-2022 走看看