WebView2中C#和JavaScript代码互操作

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

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

  [ClassInterface(ClassInterfaceType.AutoDual)]
    [ComVisible(true)]
    /// 
    /// 网页调用C#方法
    /// 
    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(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] +
					 "
"; } msg = "Message Object is a Proxy - properties can't be iterated:

" + msg; document.getElementById('MessageInfo').innerHTML = msgObject.Message + // direct access works "
" + msgObject.Number + "
" + "Active: " + msgObject["IsActive"] + // Property Indexer works "

" + 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;
		}

 

你可能感兴趣的:(.NET,WebView2,C#,JavaScript)