鸿蒙 原生与H5混合开发

本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新

一、基础交互方案

1. 使用Web组件加载H5页面

// 在ArkTS中嵌入Web组件
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController();

  build() {
    Column() {
      Web({
        src: $rawfile("index.html"), // 加载本地H5页面
        controller: this.controller
      })
      .width('100%')
      .height('100%')
    }
  }
}

2. 配置Web环境

resources/rawfile目录下放置H5资源:

resources/
  rawfile/
    index.html
    js/
      app.js
    css/
      style.css

二、H5调用原生能力

1. 注册JavaScript接口

// ArkTS侧注册JS接口
this.controller.registerJavaScriptProxy({
  // 注册原生方法
  showToast: (message: string) => {
    prompt.showToast({
      message: message,
      duration: 3000
    });
  },
  
  // 获取设备信息
  getDeviceInfo: () => {
    return {
      model: device.deviceInfo.model,
      osVersion: device.deviceInfo.osFullName
    };
  }
}, "nativeBridge"); // 命名空间

2. H5侧调用方式

// 在H5的JavaScript中调用原生方法
// 方式1:直接调用
nativeBridge.showToast("Hello from H5!");

// 方式2:异步调用获取返回值
nativeBridge.getDeviceInfo()
  .then(info => {
    console.log("设备信息:", info);
  });

三、原生调用H5方法

1. 调用H5全局函数

// ArkTS调用H5全局函数
this.controller.runJavaScript("window.h5Function('原生调用H5')")
  .then(result => {
    console.log("执行结果:", result);
  })
  .catch(error => {
    console.error("执行错误:", error);
  });

2. 传递复杂数据

// 传递JSON数据
const data = {
  type: "notification",
  content: "系统消息",
  time: new Date().toISOString()
};

this.controller.runJavaScript(`receiveData(${JSON.stringify(data)})`);

四、双向通信增强方案

1. 自定义协议拦截

// 注册协议处理器
this.controller.onUrlLoadIntercept((event) => {
  if (event.url.startsWith("jsbridge://")) {
    // 解析自定义协议
    const params = new URL(event.url).searchParams;
    const action = params.get("action");
    
    if (action === "scan") {
      // 执行原生扫码
      this.startScan();
    }
    return { intercept: true }; // 拦截请求
  }
  return { intercept: false };
});

2. H5触发方式

// H5通过iframe发送请求
function sendNativeCommand(action, params) {
  const iframe = document.createElement('iframe');
  iframe.style.display = 'none';
  iframe.src = `jsbridge://${action}?${new URLSearchParams(params)}`;
  document.body.appendChild(iframe);
  setTimeout(() => iframe.remove(), 0);
}

// 调用示例
sendNativeCommand('scan', { type: 'qrcode' });

五、数据共享方案

1. 使用本地存储共享

// ArkTS写入数据
import dataPreferences from '@ohos.data.preferences';

async function setSharedData(key: string, value: string) {
  const prefs = await dataPreferences.getPreferences(this.context, 'shared_data');
  await prefs.put(key, value);
  await prefs.flush();
}

// H5读取方式
const value = localStorage.getItem('shared_key');

2. 使用文件系统共享

// 原生写入文件
import fileIO from '@ohos.fileio';

async function writeSharedFile(content: string) {
  const path = this.context.getFilesDir() + '/shared.json';
  await fileIO.writeFile(path, content);
}

// H5通过XHR读取
fetch('file:///data/data/com.example.app/shared.json')
  .then(response => response.json())
  .then(data => console.log(data));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值