[C#] How to call eachother between WinForm and WebView2
//C# -----------------------------------------------
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webView.CoreWebView2Ready += WebView_CoreWebView2Ready;
}
private void WebView_CoreWebView2Ready(object sender, EventArgs e)
{
webView.CoreWebView2.NavigationCompleted += CoreWebView2_NavigationCompleted;
webView.CoreWebView2.AddHostObjectToScript("MyWinForm", this);
string url = string.Format("file://{0}", Path.Combine(Application.StartupPath, "../../sample.html"));
webView.Source = new Uri(url);
}
private void CoreWebView2_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
{
}
// // Javascript -> WinForm
public void FunctionFromHTML(string s)
{
MessageBox.Show(s);
}
// Winform -> Javascript
private void CallJavascriptFunction()
{
webView.CoreWebView2.ExecuteScriptAsync("FunctionFromWinForm('Called From WinForm');");
}
private void button_call_javascript_function_Click(object sender, EventArgs e)
{
CallJavascriptFunction();
}
}
//HTML -----------------------------------------
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
// Winform -> Javascript
function FunctionFromWinForm(v) {
alert(v);
}
//Javascript -> WinForm
function CallWinFormFunction() {
window.chrome.webview.hostObjects.sync.MyWinForm.FunctionFromHTML('Called From WebView2');
}
</script>
</head>
<body>
<button onclick="CallWinFormFunction()">Call WinForm's Function</button>
</body>
</html>