1、写一个简单的html页面,用于输入日志,代码如下:
<html><head> <meta charset="UTF-8"> <script> //写日志(C#调用js) function writeLog(log) { var para = document.createElement("p"); var text = document.createTextNode(log); para.appendChild(text); document.getElementById("logID").appendChild(para); } //写日志(js调用C#) function callC(){ window.external.callC(); }script>head><body> <div> <button onclick="callC()">js调用C#方法button>div> <div id="logID" style="height: 100px;width: 300px;">div>body>html>
用浏览器打开,效果如下:
2、C#项目中新建【WebBrowserUC】组件,组件继承【WebBrowser】
//浏览器页面初始化完成public event HandledEventHandler webBrowserInitComplete;//js调用C#方法public event HandledEventHandler jsCallEvent;public WebBrowserUC(){ InitializeComponent(); this.ParentChanged += WebBrowserUC_ParentChanged; this.ScrollBarsEnabled = false;}/// /// 因没有loaded事件,用ParentChanged代替,进入一次后,需要移除事件,不然重复调用/// /// /// private void WebBrowserUC_ParentChanged(object sender, EventArgs e){ try { this.ParentChanged -= WebBrowserUC_ParentChanged; string urlPath = AppDomain.CurrentDomain.BaseDirectory + "jstest\\test.html"; this.Url = new Uri(urlPath); this.DocumentCompleted += WebBrowserUC_DocumentCompleted; } catch (Exception) { }}/// /// html加载完成事件/// /// /// private void WebBrowserUC_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e){ this.DocumentCompleted -= WebBrowserUC_DocumentCompleted; if (webBrowserInitComplete != null) { webBrowserInitComplete(null, null); }}/// /// 写日志(C#调用js)/// public void writeLog(string log){ this.Document.InvokeScript("writeLog", new object[] { log });}/// /// 写日志(js调用C#)/// public void callC(){ if (jsCallEvent != null) { jsCallEvent(null, null); }}
3、新建Form窗体,将WebBrowserUC控件加入左边Panel,右边Panle放一个RichTextBox控件,用于输入js调用C#方法的日志
private WebBrowserUC webBrowserUC;public Form2(){ InitializeComponent();}private void Form2_Load(object sender, EventArgs e){ //添加浏览器控件 webBrowserUC = new WebBrowserUC(); webBrowserUC.Dock = DockStyle.Fill; //浏览器页面加载完成事件 webBrowserUC.webBrowserInitComplete += webBrowserUC_webBrowserInitComplete; webBrowserUC.jsCallEvent += webBrowserUC_jsCallEvent; panel_browser.Controls.Add(webBrowserUC);}/// /// 浏览器页面加载完成/// /// /// private void webBrowserUC_webBrowserInitComplete(object sender, HandledEventArgs e){ richTextBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+":浏览器页面加载完成\n");}/// /// 调用js方法/// /// /// private void btn_js_Click(object sender, EventArgs e){ string log = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":C#调用js方法成功"; webBrowserUC.writeLog(log);}/// /// js调用C#方法/// /// /// private void webBrowserUC_jsCallEvent(object sender, HandledEventArgs e){ richTextBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":js调用C#方法成功\n");}
4、运行C#程序,C#调用js方法正常,但是js调用C#方法报js错误,错误内容为找不到方法。
5、原因是WebBrowserUC必须加上注解[ComVisibleAttribute(true)] ,设定com可见,以便js可调用,还必须在构造函数加入这句代码,设定js的调用对象:this.ObjectForScripting = this;
1.6、再次运行c#程序,js调用C#方法和C#调用js方法均正常。
至此JS函数和winform函数之间的相互调用功能完成