C# 使用Microsoft Edge WebView2的相关总结
一、C#和JS互相调用
1、js调用C#
C#代码如下:
webView.CoreWebView2.AddHostObjectToScript("webBrowserObj",newScriptCallbackObject());
awaitwebView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("varwebBrowserObj=window.chrome.webview.hostObjects.webBrowserObj;");
像网页里面注入变量,这样网页调用时候不用每次写window.chrome.webview.hostObjects.webBrowserObj调用,最主要的是为了兼容之前cef里面Js的写法。
[ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] //////网页调用C#方法 /// publicclassScriptCallbackObject { publicstringUserName{get;set;}="我是C#属性"; publicvoidShowMessage() { MessageBox.Show("网页调用C#"); } publicvoidShowMessageArg(stringarg) { MessageBox.Show("【网页调用C#】:"+arg); } publicstringGetData(stringarg) { return"【网页调用C#获取数据】;"+arg; } [System.Runtime.CompilerServices.IndexerName("Items")] publicstringthis[intindex] { get{returnm_dictionary[index];} set{m_dictionary[index]=value;} } privateDictionarym_dictionary=newDictionary (); }
JS调用如下;
functioncallCsharp2(){
vardata2=$("#txtArg").attr("value");//大坑值不会时刻变化//alert(data2);vardata=$("#txtArg").val();
window.chrome.webview.hostObjects.webBrowserObj.ShowMessageArg(data);//window.chrome.webview.postMessage(data);};
asyncfunctioncallCsharp3(){
vardata=$("#txtArg").val();
varresult=awaitwebBrowserObj.GetData(data);
alert(result);
};
asyncfunctioncallCsharp4(){
constpropValue=awaitwebBrowserObj.UserName;
console.log(propValue);
alert(propValue);
};
2、C#调用JS
privatevoidcallJS_Click(objectsender,RoutedEventArgse)
{
webView.CoreWebView2.ExecuteScriptAsync("ShowMessage()");
}
privatevoidcallJSArg_Click(objectsender,RoutedEventArgse)
{
webView.CoreWebView2.ExecuteScriptAsync($"ShowMessageArg('{txtArg.Text}')");
}
privateasyncvoidcallJSGetData_Click(objectsender,RoutedEventArgse)
{
varjsResult=awaitwebView.CoreWebView2.ExecuteScriptAsync($"GetData('{txtArg.Text}')");
if(!string.IsNullOrEmpty(jsResult))
{
MessageBox.Show(jsResult);
}
}
js里面的代码
//2、C#调用网页
varjsVar='123';
functionHello(){
alert('调用Js'+jsVar);
};
functionShowMessage(){
alert('我是网页');
};
functionShowMessageArg(arg){
alert('【我是网页消息框】'+arg);
};
functionGetData(arg){
return'【我是网页返回给你】:'+arg;
};
二、缩放问题
webView.CoreWebView2.Settings.IsZoomControlEnabled=false;
只能禁止鼠标缩放,不能禁止手势缩放。见问题
另外触摸到底部门的时候有弹跳,暂时也无法解决。
以上就是C#使用MicrosoftEdgeWebView2的相关总结的详细内容,更多关于C#使用MicrosoftEdgeWebView2的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。