有时我们需要在WebBrowser控件中嵌入了网页,然后通过html页面调用后台方法,如何实现呢?其实很简单,主要有三步:
在被调用方法所属的类上加上[ComVisible(true)]标签,意思就是当前类可以以com组件的形式供外部调用。在WebBrowser控件中设置可被html页面调用的类即:webBrowser1.ObjectForScripting = this。前端即可通过window.external访问this对象html页面调用后台方法:window.external.方法名()。此处的window.external相当于webBrowser1.ObjectForScripting
示例代码:
一、后台
using System;using System.Runtime.InteropServices;using System.Windows.Forms;namespace jsInWebBrowserCallCSharpMethod{[ComVisible(true)]//1、必须设置且为true,否则设置webBrowser1.ObjectForScripting对象时会报错public partial class Form1 : Form{public Form1(){InitializeComponent();webBrowser1.Url =new Uri( Application.StartupPath + "\\htmls\\test.html");webBrowser1.ObjectForScripting= this;//2、设置js中window.external对象代表的类 }/// <summary>/// 供webBrowser页面中js调用的方法/// </summary>/// <param name="msg"></param>
/// <param name="msg2"></param>public void ShowMessage(string msg, string msg2){MessageBox.Show(msg + "\r\n" + msg2);}}}
二、test.html文件
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html xmlns="/1999/xhtml"><head><title>测试调用winform后台方法页面</title><script type="text/javascript">window.onload = function () {var btn = document.getElementById('btnCallCSharpMethod');btn.onclick = function () {//此处window.external相当于winform中设置的webBrowser.ObjectForScripting对象window.external.ShowMessage('成功调用winform类中的方法!','成功调用winform类中的方法2!');}}</script></head><body style='text-align:center;'><input type='button' id='btnCallCSharpMethod' value='调用winform类中的方法' /></body></html>
三、运行效果
本文转载自:/taoerchun/article/details/49782739