软件编程
位置:首页>> 软件编程>> C#编程>> C# 使用Microsoft Edge WebView2的相关总结

C# 使用Microsoft Edge WebView2的相关总结

作者:ColorsWin  发布时间:2023-02-09 16:51:12 

标签: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;

只能禁止鼠标缩放,不能禁止手势缩放。 见问题 

另外触摸到底部门的时候 有弹跳,暂时也无法解决。

来源:https://www.cnblogs.com/ColorsWin/p/14440412.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com