一、C#和JS互相調(diào)用 1、js調(diào)用C# C#代碼如下: webView.CoreWebView2.AddHostObjectToScript("webBrowserObj", new ScriptCallbackObject()); await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("var webBrowserObj= window.chrome.webview.hostObjects.webBrowserObj;"); 像網(wǎng)頁里面注入變量,這樣網(wǎng)頁調(diào)用時(shí)候不用每次寫window.chrome.webview.hostObjects.webBrowserObj調(diào)用,最主要的是為了兼容之前cef里面Js的寫法。 [ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] /// <summary> /// 網(wǎng)頁調(diào)用C#方法 /// </summary> public class ScriptCallbackObject { public string UserName { get; set; } = "我是C#屬性"; public void ShowMessage() { MessageBox.Show("網(wǎng)頁調(diào)用C#"); } public void ShowMessageArg(string arg) { MessageBox.Show("【網(wǎng)頁調(diào)用C#】:" + arg); } public string GetData(string arg) { return "【網(wǎng)頁調(diào)用C#獲取數(shù)據(jù)】;" + arg; } [System.Runtime.CompilerServices.IndexerName("Items")] public string this[int index] { get { return m_dictionary[index]; } set { m_dictionary[index] = value; } } private Dictionary<int, string> m_dictionary = new Dictionary<int, string>(); } JS調(diào)用如下; function callCsharp2() { var data2 = $("#txtArg").attr("value"); //大坑 值不會時(shí)刻變化 window.chrome.webview.hostObjects.webBrowserObj.ShowMessageArg(data); async function callCsharp3() { var data = $("#txtArg").val(); var result = await webBrowserObj.GetData(data); alert(result); }; async function callCsharp4() { const propValue = await webBrowserObj.UserName; console.log(propValue); alert(propValue); }; 2、C#調(diào)用JS private void callJS_Click(object sender, RoutedEventArgs e) { webView.CoreWebView2.ExecuteScriptAsync("ShowMessage()"); } private void callJSArg_Click(object sender, RoutedEventArgs e) { webView.CoreWebView2.ExecuteScriptAsync($"ShowMessageArg('{txtArg.Text}')"); } private async void callJSGetData_Click(object sender, RoutedEventArgs e) { var jsResult = await webView.CoreWebView2.ExecuteScriptAsync($"GetData('{txtArg.Text}')"); if (!string.IsNullOrEmpty(jsResult)) { MessageBox.Show(jsResult); } } js里面的代碼 //2、C#調(diào)用網(wǎng)頁 var jsVar = '123'; function Hello() { alert('調(diào)用Js' + jsVar); }; function ShowMessage() { alert('我是網(wǎng)頁'); }; function ShowMessageArg(arg) { alert('【我是網(wǎng)頁消息框】' + arg); }; function GetData(arg) { return '【我是網(wǎng)頁返回給你】:' + arg; };
二、縮放問題 webView.CoreWebView2.Settings.IsZoomControlEnabled = false; 只能禁止鼠標(biāo)縮放,不能禁止手勢縮放。 見問題 另外觸摸到底部門的時(shí)候 有彈跳,暫時(shí)也無法解決。
|
|