1 回答
TA贡献1831条经验 获得超4个赞
假设这是 WinForms,因为有一个 WebBrowser 控件,从 HTML 页面 JavaScript 调用 C# 代码可以用这个最小的例子来完成:
将简单的 HTML 页面添加到项目的根目录并Properties设置为此Copy to Output Directory: Copy if newer将确保有一个简单的页面用于测试:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>WebForms WebBrowser Control Client</title>
</head>
<body>
<input type="button" onclick="getLocations()" value="Call C#" />
<script type="text/javascript">
function getLocations() {
var locations = window.external.SendLocations();
alert(locations);
}
</script>
</body>
</html>
JS函数getLocations会调用C#方法SendLocations,重要的部分是Form1类注解和设置webBrowser1.ObjectForScripting = this:
using System.Windows.Forms;
using System.Security.Permissions;
using System.IO;
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ObjectForScripting = this;
var path = Path.GetFullPath("Client.html");
var uri = new Uri(path);
webBrowser1.Navigate(uri);
}
public string SendLocations()
{
return "SF, LA, NY";
}
}
单击 HTML 按钮Call C#将显示一个弹出窗口,其中包含 C# 方法的返回值
添加回答
举报