HarmonyOS鸿蒙Next中使用Web组件加载本地网页时,如何在本地网页中调用ArkTS中的函数

HarmonyOS鸿蒙Next中使用Web组件加载本地网页时,如何在本地网页中调用ArkTS中的函数 解决措施

  1. 准备一个 HTML 文件,例如:
<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title>Document</title> 
</head> 
<body> 
    <h1>标题</h1> 
    <h5 id="h5"></h5> 
    <h5 id="h6"></h5> 
    <button onclick="handleFromH5">调用 Arkts 的方法</button> 
    <script type="text/javascript"> 
        function handleFromH5(){ 
            let result = window.objName.test(); 
            document.getElementById('h6').innerHTML = result; 
        } 
    </script> 
</body> 
</html>
  1. 在 ArkTs 中使用 JavaScriptProxy 方法将 ArkTs 里的对象注册到 H5 的 window 对象中,然后在 h5 中使用 window 对象调用该方法。比如下面例子,在 ArkTs 中将 testObj 这个对象以别名 objName 注册到 h5 的 window 对象上,在上面的 h5 中就可以使用 window.objName 去访问这个对象。
// xxx.ets 
import { webview } from '@kit.ArkWeb' 

class TestObj { 
  constructor() { 
  } 
  test(data1: string, data2: string, data3: string): string { 
    console.log("data1:" + data1) 
    console.log("data2:" + data2) 
    console.log("data3:" + data3) 
    return "AceString" 
  } 
  toString(): void { 
    console.log('toString' + "interface instead.") 
  } 
} 

@Entry 
@Component 
struct Index { 
  @State message: string = 'Hello World' 
  controller: webview.WebviewController = new webview.WebviewController() 
  testObj = new TestObj(); 
  build() { 
    Row() { 
      Column() { 
        Web({ src:$rawfile('index.html'), controller:this.controller }) 
          .javaScriptAccess(true) 
          .javaScriptProxy({ 
            object: this.testObj, 
            name: "objName", 
            methodList: ["test", "toString"], 
            controller: this.controller, 
         }) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
}

参考链接

javaScriptProxy


更多关于HarmonyOS鸿蒙Next中使用Web组件加载本地网页时,如何在本地网页中调用ArkTS中的函数的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

请问如何创建对象的属性,比如:

window.plugins.nativePlugin.version()
window.plugins.urlPlugin.jumpUrl()

javaScriptProxy貌似只能创建一个对象下的方法列表,以上格式的对象要怎么写呢

.javaScriptProxy({
  object: this.testObj, 
  name: "plugins", 
  methodList: ["urlPlugin", "nativePlugin"], 
  controller: this.controller, 
})

可是每个插件下又有多个方法,要怎么写?

更多关于HarmonyOS鸿蒙Next中使用Web组件加载本地网页时,如何在本地网页中调用ArkTS中的函数的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


请问解决了吗

在HarmonyOS鸿蒙Next中,可以通过WebControllerpostMessage实现本地网页调用ArkTS函数。首先,在ArkTS中通过WebController监听onMessageEvent事件,接收网页发送的消息。然后在网页中使用window.parent.postMessage发送消息给ArkTS。ArkTS接收到消息后,根据消息内容执行相应的函数。具体步骤如下:

  1. ArkTS中设置WebController监听:

    webController.onMessageEvent((event) => {
        if (event.data === 'callFunction') {
            // 执行ArkTS函数
        }
    });
    
  2. 网页中使用postMessage发送消息:

    window.parent.postMessage('callFunction', '*');
    

通过这种方式,实现本地网页与ArkTS的交互。

回到顶部