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

2025-10-28 17:14:41

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

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢