HarmonyOS鸿蒙Next中JS如何调用原生接口

HarmonyOS鸿蒙Next中JS如何调用原生接口 如题,我们这边有个项目想要从JS上调用鸿蒙原生接口,这个有相关的指导嘛

5 回复

开发者您好,鸿蒙提供了一种名为JS Framework的框架,可以帮助JS开发者调用鸿蒙原生接口。

方舟开发框架提供了两种开发范式,声明式开发范式和类Web开发范式,JS开发可以参考类Web开发范式。

参考文档:https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ui-js-overview-0000001333721061

更多关于HarmonyOS鸿蒙Next中JS如何调用原生接口的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


@Entry @Component struct Index { controller: WebController = new WebController() testObj = { test: (data) => { return “ArkUI Web Component”; }, toString: () => { console.log(‘Web Component toString’); } } build() { Column() { Row() { Button(‘Register JavaScript To Window’).onClick(() => { this.controller.registerJavaScriptProxy({ object: this.testObj, name: “objName”, methodList: [“test”, “toString”], }); }) } Web({ src: $rawfile(‘index.html’), controller: this.controller }) .javaScriptAccess(true) } } }

用这个registerJavaScriptProxy,name和window中调用名字一致就可以.methodList是name下的方法名 也可以用js调用confirm然后原生用onComfirm监听

什么是鸿蒙原生接口?

在HarmonyOS鸿蒙Next中,JS调用原生接口主要通过@ohos.xxx模块实现。开发者可以使用import语句导入所需的原生模块,然后直接调用模块中的方法。例如,调用系统能力接口时,可以使用@ohos.systemCapability模块。具体步骤如下:

  1. 导入模块:使用import语句导入需要调用的原生模块。例如,import systemCapability from '@ohos.systemCapability'

  2. 调用接口:通过导入的模块直接调用原生接口。例如,systemCapability.getSystemInfo()可以获取系统信息。

  3. 处理返回结果:根据接口返回的数据类型进行处理。例如,getSystemInfo()返回的是一个对象,可以通过console.log输出或进一步处理。

  4. 错误处理:使用try-catch语句捕获并处理可能出现的异常。

示例代码:

import systemCapability from '@ohos.systemCapability';

try {
    let systemInfo = systemCapability.getSystemInfo();
    console.log(JSON.stringify(systemInfo));
} catch (error) {
    console.error('Failed to get system info:', error);
}

在HarmonyOS鸿蒙Next中,JS调用原生接口主要通过@ohos模块实现。首先,在js文件中导入相关模块,如@ohos.xxx。然后,通过模块提供的API调用原生功能。例如,调用系统弹窗:

import prompt from '@ohos.prompt';

prompt.showToast({
  message: 'Hello, HarmonyOS!'
});

确保在config.json中声明所需权限和模块。这种方式实现了JS与原生代码的交互,提升了应用的功能性和性能。

回到顶部