C#使用Microsoft Edge WebView2记录
一、C#和JS互相调用
1、js调用C#
C#代码如下:
webView.CoreWebView2.AddHostObjectToScript("webBrowserObj", new ScriptCallbackObject());
await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("var webBrowserObj= window.chrome.webview.hostObjects.webBrowserObj;");
像网页里面注入变量,这样网页调用时候不用每次写window.chrome.webview.hostObjects.webBrowserObj调用,最主要的是为了兼容之前cef里面Js的写法。
[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调用如下;
function callCsharp2() {
var data2 = $("#txtArg").attr("value"); //大坑 值不会时刻变化
// alert(data2);
var data = $("#txtArg").val();
window.chrome.webview.hostObjects.webBrowserObj.ShowMessageArg(data);
//window.chrome.webview.postMessage(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#调用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#调用网页 var jsVar = '123'; function Hello() { alert('调用Js' + jsVar); }; function ShowMessage() { alert('我是网页'); }; function ShowMessageArg(arg) { alert('【我是网页消息框】' + arg); }; function GetData(arg) { return '【我是网页返回给你】:' + arg; };
二、缩放问题
webView.CoreWebView2.Settings.IsZoomControlEnabled = false;
只能禁止鼠标缩放,不能禁止手势缩放。 见问题
另外触摸到底部门的时候 有弹跳,暂时也无法解决。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?