[Winform-WebBrowser]-在html页面中js调用winForm类方法

时间:2023-03-08 16:38:18

在winform项目中嵌入了网页,想通过html页面调用后台方法,如何实现呢?其实很简单,主要有三部:

1、在被调用方法类上加上[ComVisible(true)]标签,意思就是当前类可以com组件的形式供外包调用

2、在webBrowser控件中设置可被html页面调用的类即:webBrowser1.ObjectForScripting = this;前端即可通过window.external访问this对象

3、html页面调用后台方法:window.external.方法名(); 此处的window.external相当于webBrowser1.ObjectForScripting

    //ComVisible 设置对外的可访问性,在html中可使用 js 访问成员方法
[ComVisible(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
//browser.Url = new Uri("https://www.baidu.com");
browser.Url = new Uri("http://localhost:3133/index.html");
browser.ObjectForScripting = this;
} private void btnSearch_Click(object sender, EventArgs e)
{
HtmlElement kw = browser.Document.All["kw"];
HtmlElement btn = browser.Document.All["su"]; string txt = txtwd.Text.Trim();
kw.SetAttribute("value", txt);
btn.InvokeMember("click");
} private void btnDo_Click(object sender, EventArgs e)
{
int[] arr = { , };
browser.Document.InvokeScript("f",new object[] { "{1,2,3}" });
} public void WinF(string arg)
{
MessageBox.Show(arg);
}
}

html 代码:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<h1>Hello World!</h1> <button onclick="ext()">external</button> <script> var f = function (msg) {
//if()
alert(Object.prototype.toString.call(msg));
}
//调用winform 中的方法
function ext() {
//调用winform 中的方法
window.external.WinF("hello");
} </script> </body>
</html>