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# 方法的返回值
添加回答
舉報