6

WebView2简单试用(七)—— WebMessage

 3 years ago
source link: https://www.cnblogs.com/TianFang/p/14375713.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

之前文章中介绍过通过JS实现WebView2宿主程序和前端页面进行通信的方法。在WebView2中,更加通用而高效的方式是WebMessage,它是一个异步的消息通信,并且支持双向通信,本文这里简单的介绍下其用法。

前端页面发送消息给宿主程序:

首先,在WebView中定义接收到消息的处理函数:

    webView.WebMessageReceived += (s, e) =>
    {
        MessageBox.Show(e.WebMessageAsJson);
    };

PS:这个事件在CoreWebView2上也有,使用效果是一样的。

然后,在前端脚本中发送消息:    

    chrome.webview.postMessage('hello world')

执行效果如下:

宿主程序发消息给前端页面:

首先,前端注册消息的处理函数:

    chrome.webview.addEventListener('message', event => alert(event.data));

然后,CoreWebView2.PostWebMessageAsXXX函数发送消息

    webView.CoreWebView2.PostWebMessageAsString("hello world");

执行效果如下:

禁用WebMessage:

如果为了安全起见,也可以通过设置将其禁用:

    webView.CoreWebView2.Settings.IsWebMessageEnabled = false;

参考文章:

主机和 Web 内容之间的通信


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK