鸿蒙Next中H5与JSBridge交互如何实现

在鸿蒙Next系统中,H5页面如何通过JSBridge与原生代码进行通信?具体需要调用哪些接口或方法?能否提供完整的交互流程示例,包括H5调用原生功能以及原生回调H5的实现方式?另外,鸿蒙Next的JSBridge与Android/iOS平台有哪些差异需要注意?

2 回复

在鸿蒙Next里,H5和JSBridge交互就像两个程序员隔墙喊话:H5用window.ohos.callNative()喊"嘿,哥们!",JSBridge用WebController.executeJs()回"收到!"。记得在config.json里配好路由,不然消息就迷路啦~

更多关于鸿蒙Next中H5与JSBridge交互如何实现的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙Next(HarmonyOS NEXT)中,H5与JSBridge交互通过Web组件和WebMessagePort实现双向通信。以下是关键步骤和代码示例:

1. H5页面调用原生方法

  • 前端发送消息

    // H5页面中,通过WebMessagePort发送消息
    if (window.hap && window.hap.WebView) {
      const port = window.hap.WebView.createWebMessagePort();
      port.postMessage("Hello from H5");
    }
    
  • ArkTS侧监听消息

    // 在ArkUI中配置Web组件
    import webview from '[@ohos](/user/ohos).web.webview';
    
    [@Entry](/user/Entry)
    [@Component](/user/Component)
    struct WebComponent {
      controller: webview.WebviewController = new webview.WebviewController();
    
      build() {
        Column() {
          Web({ src: 'www.example.com', controller: this.controller })
            .onPageEnd(() => {
              // 注册消息端口
              this.controller.registerWebMessagePort("channelName", (messagePort: webview.WebMessagePort) => {
                messagePort.onMessage((data: string) => {
                  console.log('Received from H5: ' + data); // 输出:Hello from H5
                });
              });
            })
        }
      }
    }
    

2. 原生调用H5方法

  • ArkTS发送消息

    // 通过已建立的WebMessagePort向H5发送数据
    messagePort.postMessage("Hello from ArkTS");
    
  • H5接收消息

    // H5监听消息
    if (window.hap && window.hap.WebView) {
      const port = window.hap.WebView.createWebMessagePort();
      port.onmessage = (event) => {
        console.log('Received from ArkTS: ' + event.data); // 输出:Hello from ArkTS
      };
    }
    

3. 关键注意事项

  • 安全机制:需在module.json5中配置ohos.permission.INTERNET权限。
  • 端口管理:确保消息端口在页面跳转或销毁时正确关闭。
  • 数据格式:支持字符串传输,复杂数据需序列化(如JSON)。

总结

通过WebMessagePort实现双向通信,H5与原生端可互发消息。此方案替代了传统JavaScriptProxy,更符合鸿蒙Next的架构规范。实际开发中需注意生命周期管理和异常处理。

回到顶部