Skip to content

02 Messaging

starTechnology1994 edited this page Aug 7, 2026 · 1 revision

02 双向通讯

WebNativeBrowser 使用 FunctionName + MessageBody 形式在网页与 UE 之间交换业务消息,两端均提供简单一致的 API。且消息通道拥有极致的性能10万+消息只需要200ms就能处理完成


1. 通信架构

  • JS → UE:网页调用 WebNative.send(functionName, messageBody),UE 侧触发 OnMessageReceived 事件。
  • UE → JS:UE 调用 SendMessageToJS(functionName, messageBody),网页侧 WebNative.on(functionName, handler) 回调被触发。

2. JS → UE(网页发消息)

2.1 基本调用

WebNative.send("FunctionName", messageBody);

messageBody 支持多种类型,插件自动转换:

WebNative.send("OnText", "hello");                    // 字符串
WebNative.send("OnNumber", 42);                       // 数字
WebNative.send("OnBoolean", true);                    // 布尔
WebNative.send("OnObject", { id: 1001, name: "设备 A" }); // 对象 → 自动 JSON 序列化
WebNative.send("OnEmpty", null);                      // 空

2.2 类型映射

UE 端统一收到字符串

JS 输入 UE 收到的 MessageBody
对象 JSON 字符串
字符串 原始字符串
数字 数字对应的字符串
布尔值 truefalse 字符串
null / undefined 空字符串

对象由插件在网页端转换为 JSON 字符串,业务层不需要提前 JSON.stringify();传入已经序列化的字符串也兼容。

2.3 UE 端接收

绑定 OnMessageReceived 事件,收到两个参数:FunctionNameMessageBody。蓝图中先判断 FunctionName,再按业务需要解析。


3. UE → JS(UE 发消息)

3.1 UE 调用

调用 SendMessageToJS(蓝图/C++ 均可),传入 FunctionName 和字符串类型的 MessageBody

FunctionName: PlayerState
MessageBody: {"hp":100,"level":5}

3.2 网页订阅

function onPlayerState(messageBody) {
  const state = JSON.parse(messageBody);
  console.log(state.hp);
}

WebNative.on("PlayerState", onPlayerState);

// 不再需要时解除订阅
WebNative.off("PlayerState", onPlayerState);

JS 回调始终收到原始字符串。插件不会自动调用 JSON.parse()——纯文本、数字文本和 JSON 都是合法业务消息,只有业务明确它是 JSON 时才解析。


4. 顺序与线程

  • 同一路径中按调用顺序投递消息。
  • UE 的 UObject 和场景操作必须在 UE 游戏线程完成(消息自动回调到主线程)。
  • 收到消息后不要在回调中执行长时间阻塞任务;可拆分业务处理,再将最终结果发送给网页。
  • 业务层不要同时从多个异步源修改同一状态而不做版本控制。

5. 调试清单

  • 确认 window.WebNative 已经可用(页面加载完成后再调用)。
  • 确认 FunctionName 大小写完全一致。
  • 确认事件没有被重复注册(组件卸载时 off)。
  • 确认 JSON 只在业务明确为 JSON 时解析。
  • 高频调试时避免每条消息都更新 DOM 或打印完整大对象。

下一步

Clone this wiki locally