1、C#和JS互相調用 git
一、js調用C# github
C#代碼以下:web
webView.CoreWebView2.AddHostObjectToScript("webBrowserObj", new ScriptCallbackObject());chrome
await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("var webBrowserObj= window.chrome.webview.hostObjects.webBrowserObj;");async
像網頁裏面注入變量,這樣網頁調用時候不用每次寫window.chrome.webview.hostObjects.webBrowserObj調用,最主要的是爲了兼容以前cef裏面Js的寫法。post
[ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] /// <summary> /// 網頁調用C#方法 /// </summary> public class ScriptCallbackObject { public string UserName { get; set; } = "我是C#屬性"; public void ShowMessage() { MessageBox.Show("網頁調用C#"); } public void ShowMessageArg(string arg) { MessageBox.Show("【網頁調用C#】:" + arg); } public string GetData(string arg) { return "【網頁調用C#獲取數據】;" + 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調用以下;this
function callCsharp2() {spa
var data2 = $("#txtArg").attr("value"); //大坑 值不會時刻變化
// alert(data2);
var data = $("#txtArg").val(); code
window.chrome.webview.hostObjects.webBrowserObj.ShowMessageArg(data);
//window.chrome.webview.postMessage(data);
};blog
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); };
二、C#調用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裏面的代碼
//二、C#調用網頁 var jsVar = '123'; function Hello() { alert('調用Js' + jsVar); }; function ShowMessage() { alert('我是網頁'); }; function ShowMessageArg(arg) { alert('【我是網頁消息框】' + arg); }; function GetData(arg) { return '【我是網頁返回給你】:' + arg; };
2、縮放問題
webView.CoreWebView2.Settings.IsZoomControlEnabled = false;
只能禁止鼠標縮放,不能禁止手勢縮放。 見問題
另外觸摸到底部門的時候 有彈跳,暫時也沒法解決。