首先为WebBrowser添加页面
string p = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
p = p.Substring(0, p.LastIndexOf("\\"));
p = p.Substring(0, p.LastIndexOf("\\"));
p = p.Substring(0, p.LastIndexOf("\\"));
p += string.Format("\\HTML\\test.html");
Uri u = new Uri(p);//获取页面路径
this.webBrowser1.Url = u;
//webBrowser1.Navigate(p);
上面的代码,把录入url换成下面注释的同样好用(VS2015实测有效)
接下来调用页面上的js
HtmlDocument doc = webBrowser1.Document;
String str = (string)doc.InvokeScript("test");
//需要添加引用:Interop.MSScriptControl
//但并不建议使用
//mshtml.IHTMLDocument2 currentDoc = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
//mshtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)currentDoc.parentWindow;
//string a=win.execScript("test()", "javascript");
有需要注意的事项:
1.必须等到界面加载完毕,然后操作js。建议先放置一个按钮,然后点击按钮操作js测试
2.上面未注释的调用方式与下面注释的调用方式同样可以调用,但测试时发现下面注释的调用方式无法获取返回值,不建议使用