IE浏览器控制,C#利用JS操作IE

 时间:2026-02-17 08:01:20

1、先打开一个IE浏览器窗口,新建一个C#项目右击项目目录的【引用】,添加引用。在.NET选项卡添加名字为【Microsoft.mshtml】的引用

IE浏览器控制,C#利用JS操作IE

2、在COM中添加名称为【Microsoft Internet Controls】的引用

IE浏览器控制,C#利用JS操作IE

3、写一个jsRun的方法,方便频繁的向浏览器的指定网页中动态执行JS脚本其中Brower传递我们要执行脚本的对象,而str是我们想要执行的js:

         private void jsRun(InternetExplorer Browser,String str)

        {

            HTMLDocument doc = Browser.Document as HTMLDocument;

            HTMLScriptElement script = (HTMLScriptElement)doc.createElement("script");

            script.text = str;

            HTMLBody body = doc.body as HTMLBody;

            body.appendChild((IHTMLDOMNode)script);

        }

IE浏览器控制,C#利用JS操作IE

4、在Form1中执行jsRun的调用:

        private void Form1_Load(object sender, EventArgs e)

        {

            ShellWindows shellWindows = new ShellWindowsClass();

            foreach (InternetExplorer Browser in shellWindows)

            {

                if (Browser.Document is HTMLDocument)

                {

                    jsRun(Browser, "alert(889966);");

                    jsRun(Browser, "alert(00000);");

                }

            }

        }

IE浏览器控制,C#利用JS操作IE

5、完整代码如下:

#region Using directives

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using mshtml;

using SHDocVw;

#endregion

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            ShellWindows shellWindows = new ShellWindowsClass();

            foreach (InternetExplorer Browser in shellWindows)

            {

                if (Browser.Document is HTMLDocument)

                {

                    jsRun(Browser, "alert(889966);");

                    jsRun(Browser, "alert(00000);");

                }

            }

        }

         private void jsRun(InternetExplorer Browser,String str)

        {

            HTMLDocument doc = Browser.Document as HTMLDocument;

            HTMLScriptElement script = (HTMLScriptElement)doc.createElement("script");

            script.text = str;

            HTMLBody body = doc.body as HTMLBody;

            body.appendChild((IHTMLDOMNode)script);

        }

    }

}

IE浏览器控制,C#利用JS操作IE

6、执行结果是Form1中连续调用两次jsRun,浏览器都能先后执行效果如下图。此案例为外部程序向IE注入js脚本控制网页元素的demo案例。

IE浏览器控制,C#利用JS操作IE

IE浏览器控制,C#利用JS操作IE

  • 剑网3怎么获得企鹅表情
  • kali怎么改成全命令行
  • 聚合码收款码怎么申请
  • 使用winpe绕过系统密码
  • 新安装的系统win11版本号怎么看
  • 热门搜索
    科技手抄报大全 环境手抄报 二年级手抄报图片 美丽的家乡手抄报 六年级手抄报 奥运会手抄报内容 安全手抄报版面设计图 关于国庆节的英语手抄报 防踩踏手抄报 中国神话故事手抄报