1、先打开一个IE浏览器窗口,新建一个C#项目右击项目目录的【引用】,添加引用。在.NET选项卡添加名字为【Microsoft.mshtml】的引用
2、在COM中添加名称为【Microsoft Internet Controls】的引用
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); }
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);"); } } }
5、完整代码如下:#region Using directivesusing 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;#endregionnamespace 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); } }}
6、执行结果是Form1中连续调用两次jsRun,浏览器都能先后执行效果如下图。此案例为外部程序向IE注入js脚本控制网页元素的demo案例。