WebView2 系列之- ts 向 c# 传递文件对象

背景#

WebView2 中,前端到后端的消息传递,通常是不支持传递对象的。但是我在查阅官方文档时发现了一个例外,那就是方法postMessageWithAdditionalObjects

如何传递附加对象#

webview2中,前端 js 向后端传递消息通常使用 window.chrome.webview.postMessage 方法,postMessage的定义如下:

     /**
     * When the page calls postMessage, the message parameter is converted to JSON and is posted
     * asynchronously to the WebView2 host process. This will result in either the
     * CoreWebView2.WebMessageReceived event or the CoreWebView2Frame.WebMessageReceived event being
     * raised, depending on if postMessage is called from the top-level document in the WebView2
     * or from a child frame. See CoreWebView2.WebMessageReceived( Win32/C++, .NET, WinRT).
     * See CoreWebView2Frame.WebMessageReceived( Win32/C++, .NET, WinRT).
     * @param message The message to send to the WebView2 host. This can be any object that can be
     *                serialized to JSON.
     */
    postMessage(message: any) : void;

当我们使用postMessage传递任何数据类型时,都将被转为 json 字符串进行传递。

postMessageWithAdditionalObjects 接受两个参数,第一个参数和postMessage的参数一样,第二个参数允许传递一个 js 对象列表,它会被转换为原生代码中对应的类。

/**
     * When the page calls `postMessageWithAdditionalObjects`, the `message` parameter is sent to WebView2 in the same
     * fashion as {@link WebView.postMessage}.
     * Objects passed as 'additionalObjects' are converted to their native types and will be available in the
     * `CoreWebView2WebMessageReceivedEventArgs.AdditionalObjects` property.
     * @param message The message to send to the WebView2 host. This can be any object that can be serialized to JSON.
     * @param additionalObjects A sequence of DOM objects that have native representations in WebView2.
     * This parameter needs to be ArrayLike.
     *
     * The following DOM types are mapped to native:
     * DOM    | Win32              | .NET                | WinRT
     * ------ | ------------------ | ------------------- | ---------------------------
     * File   | ICoreWebView2File  | System.IO.FileInfo  | Windows.Storage.StorageFile
     *
     * `null` or `undefined` entries will be passed as `null` type in WebView2. Otherwise if an invalid or unsupported
     * object is passed via this API, an exception will be thrown and the message will fail to post.
     */
    postMessageWithAdditionalObjects(message: any, additionalObjects: ArrayLike<any>): void;

使用示例#

经测试,目前只支持前端的File类型,使用示例如下:

前端:

 <input id="file" type="file" value="选择文件" accept="*/*"/>
import {onMounted} from "vue";

onMounted(() => {
  const file = document.querySelector("#file") as HTMLInputElement | null;
  file?.addEventListener("change", () => {
    console.log(file.files);
    if (file.files != null) {
      window.chrome.webview.postMessageWithAdditionalObjects("files", file.files);//files的类型是 FileList
    }
  })
})

后端接收的方法:

#region 监听前端消息

webview.CoreWebView2.WebMessageReceived += CoreWebView2OnWebMessageReceived;

#endregion

private void CoreWebView2OnWebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
{
    var message = e.TryGetWebMessageAsString();
    var objs = e.AdditionalObjects;
    var a = e.Source;
    Debug.WriteLine(JsonSerializer.Serialize(objs[0]));
}

当前端选择一个图片时,前端打印选择的结果:

image

传递给后端,后端接收到的数据:

image

前端从file.files拿到的数据是没有路径的,传给后端后有了完整路径,是不是很神奇。

社区共建#

我计划创建 webview2 开发者社区,方便交流探讨相关问题。欢迎读者朋友加我微信 ysq210429 交流,添加时请备注来源网站,如博客园。

作者:sq800

出处:https://www.cnblogs.com/sq800/p/18122762

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   sq800  阅读(490)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
more_horiz
keyboard_arrow_up light_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示