WebView2中C#和JavaScript代码互操作

时间:2024-10-27 08:44:23

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

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

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

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

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

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

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

().then( function(msg) { alert(msg+'async'); }, 
                       function() { alert('failed'); })

function GetMessageInfo() {
		//;
          var  msgObject=();
		  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;

				 ('MessageInfo').innerHTML =
         +   // direct access works
        "<br/>" +
         +
        "<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 = (msgObject);
		var msg = (json);
		("MessageInfo").innerText = msg;
		}