WebView2中C#和JavaScript代码互操作

  • Post author:
  • Post category:java


C#调用或者执行前端的JavaScript

1.需要创建一个ScriptHost,并注册到WebView2中

  [ClassInterface(ClassInterfaceType.AutoDual)]
    [ComVisible(true)]
    /// <summary>
    /// 网页调用C#方法
    /// </summary>
    public class ScriptCallbackObject
//注册winning脚本c#互操作
WebViewCore.CoreWebView2.AddHostObjectToScript("winning", ScriptHost);
//注册全局变量winning
WebViewCore.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("var winning= window.chrome.webview.hostObjects.winning;");

2.ScriptHost中暴露的公共方法,都可以在前端JavaScript中调用

 public MessageInfo GetMessageInfo()
        {
            return new MessageInfo()
            {
                Message = $"Message from .NET at {DateTime.Now:t}"
            };
        }
        public string PassMessageInfo(string jsonMessageInfo)
        {
            var msg = JsonConvert.DeserializeObject<MessageInfo>(jsonMessageInfo);
            string message = $"{msg.Message} {msg.Type} {msg.Number} {msg.IsActive}";
            return message;
        }

        public string ShowMessage(string arg)
        {
            //MessageBox.Show("【网页调用C#】:" + arg);
            //里面触发事件
            //返回到绑定的方法中
            OnScriptCallBack(arg);
            return "c#回调到前端";
            //要回调到前端
            //只需要在前端使用then(),默认异步方式执行
        }

3.前端调用的C#代理默认都是异步,要同步调用需要加sync前缀

winning.ShowMessage(titleText.value).then( function(msg) { alert(msg+'async'); }, 
                       function() { alert('failed'); })

function GetMessageInfo() {
		//window.chrome.webview.hostObjects.options.forceLocalProperties;
          var  msgObject=window.chrome.webview.hostObjects.sync.winning.GetMessageInfo();
		  var msg = "";
			for(var prop in msgObject) {
				 msg += prop +
				 ": " + msgObject[prop] +
					 "<br />";
			 }
			 msg = "Message Object is a Proxy - properties can't be iterated:<br/><br/>" + msg;

				 document.getElementById('MessageInfo').innerHTML =
        msgObject.Message +   // direct access works
        "<br/>" +
        msgObject.Number +
        "<br/>" +
        "Active: " +
        msgObject["IsActive"] +   // Property  Indexer works
        "<br/ ><br />" +
        msg;
	 }
passMessageInfo: function () {
		var msgObject = {
			Message: "Hello from JavaScript",
			Type: "Warning",
			Number: 20,
			IsActive: true
		}

		var json = JSON.stringify(msgObject);
		var msg = window.chrome.webview.hostObjects.sync.winning.PassMessageInfo(json);
		document.getElementById("MessageInfo").innerText = msg;
		}



版权声明:本文为Yurixu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。