NW.js混合开发:Web与HarmonyOS 5原生能力互调的桥梁设计

0 阅读2分钟

一、JSBridge通信机制设计

  1. 双向通信实现 HarmonyOS提供javaScriptProxy代理机制实现Web与ArkTS通信。通过注入ArkTS对象到Web页面,支持函数调用及复杂参数传递:
build() {
  Column() {
    Web({ src: './Index', controller: new webview.WebviewController() })
      .javaScriptProxy({
        object: { // 注入对象
          makePhoneCall: (phoneNumber: string) => { // 方法声明
            call.makeCall(phoneNumber); // 调用系统电话服务
          }
        },
        name: "nativeObj", // Web侧调用标识
        methodList: ["makePhoneCall"], // 暴露方法列表
        controller: new webview.WebviewController()
      })
  }
}

Web侧通过window.nativeObj.makePhoneCall('123456')即可触发原生能力。 2. 通信分层架构

  • 通信层:使用WebMessagePortjavaScriptProxy传递序列化数据
  • 通道层:解析数据并分发到具体业务模块,支持多通道注册
// ArkTS侧通道处理示例
.javaScriptProxy({
  object: {
    nativeMethod: (channelType: string, objectJson: string) => {
      return ChannelRouter.dispatch(channelType, JSON.parse(objectJson));
    }
  },
  name: 'JSBridge',
  methodList: ['nativeMethod']
})

Web侧通过window.JSBridge.nativeMethod('channelName', data)调用。


二、同层渲染实现策略

  1. 原生组件嵌入 使用<embed>标签声明原生组件,通过NodeContainer动态挂载ArkUI组件树:
<!-- Web侧Vue示例 -->
<template>
  <embed 
    id="nativeComponent" 
    type="native/customView" 
    :width="300" 
    @gestureEvent="handleGesture"
  />
</template>

// ArkTS侧节点管理
class CustomController extends NodeController {
  makeNode(): UIContext.CanvasNode {
    return new CustomComponentNode(); // 自定义组件节点
  }
}
NodeContainer.bindController(CustomController());

通过enableNativeEmbedMode开启同层渲染模式。 2. 生命周期与事件处理

Web({ ... })
  .onNativeEmbedLifecycleChange((event) => {
    if (event.status === 'CREATE') {
      // 初始化节点
    } else if (event.status === 'DESTROY') {
      // 释放资源
    }
  })
  .onNativeEmbedGestureEvent((event) => {
    // 处理手势事件
  })


三、混合开发模块封装

  1. 统一接口层 封装跨平台API调用,保持Web与ArkTS接口一致性:
// Web侧适配层
const HybridStorage = {
  setItem: (key: string, value: string) => {
    window.JSBridge.nativeMethod('storage', { action: 'set', key, value });
  },
  getItem: (key: string) => {
    return window.JSBridge.nativeMethod('storage', { action: 'get', key });
  }
}

// ArkTS侧实现
class StorageChannel {
  static handle(params: Params): string {
    if (params.action === 'set') {
      dataStorage.setSync(params.key, params.value);
    }
    return dataStorage.getSync(params.key);
  }
}

  1. 动态路由管理 通过router_map.json实现页面跳转解耦:
{
  "routes": {
    "/nativeDetail": "pages/NativeDetailPage",
    "/webView": "pages/WebContainerPage"
  }
}

使用router.pushUrl()实现混合导航。


四、性能优化实践

  1. 启动加速
  • 使用AppStartUp框架延迟加载非关键模块
  • Web组件预加载策略:
const preloadController = new webview.WebviewController();
preloadController.loadUrl('preload.html');

  1. 渲染优化
  • 设置分辨率动态切换策略:
Web({ ... })
  .onRender((event) => {
    if (event.fps < 30) {
      setResolution('720p');
    }
  })

通过以上设计,可实现Web与HarmonyOS原生能力的高效互操作,同时满足元服务10MB包大小限制及性能要求。