HarmonyOS H5与原生通信,如何直接将方法挂载到window上

H5页面是已经写好且上线的, 调用原生的方式为: window.func()

HarmonyOS这边注册的话需要是一个对象, 就会导致调用需要改为 window.xxx.func()

如何在不改动H5代码的前提下 实现window.func()呢

HarmonyOS
2025-01-09 18:08:56
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zbw_apple

可以试下使用javascriptondocumentstart11直接写window.fun:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-basic-components-web-V5#javascriptondocumentstart11

// xxx.ets
import { webview } from '@kit.ArkWeb';

@Entry
@Component
struct Index {
  controller: webview.WebviewController = new webview.WebviewController();
  private localStorage: string =
    `window.test=()=>{return 'hello world from Native'}`;
  @State scripts: Array<ScriptItem> = [
    { script: this.localStorage, scriptRules: ["*"] }
  ];

  build() {
    Column({ space: 20 }) {
      Web({ src: $rawfile('index.html'), controller: this.controller })
        .javaScriptAccess(true)
        .domStorageAccess(true)
        .backgroundColor(Color.Grey)
        .javaScriptOnDocumentStart(this.scripts)
        .width('100%')
        .height('100%')
    }
  }
}

index.html

<!-- index.html -->
  <!DOCTYPE html>
  <html>
  <body>
  <button type="button" onclick="callArkTS()">Click Me!</button>
  <p id="demo"></p>
  <script>
  function callArkTS() {
    <!-- console.dir(window);-->
      let str = test();
    document.getElementById("demo").innerHTML = str;
    console.info('ArkTS Hello World! :' + str);
  }
  </script>
  </body>
  </html>
分享
微博
QQ
微信
回复
2025-01-09 20:23:05
相关问题
HarmonyOS 原生webview中的H5消息通信
1117浏览 • 1回复 待解决
HarmonyOS ArkTSH5交互方法
1226浏览 • 1回复 待解决
h5应用端的sdk通信问题
1378浏览 • 1回复 待解决
HarmonyOS H5原生交互
1286浏览 • 1回复 待解决
如何桥接鸿蒙原生H5之间的交互?
1644浏览 • 2回复 已解决
HarmonyOS h5和ArkTS通信
1389浏览 • 1回复 待解决
HarmonyOS h5 window.history 无效
1205浏览 • 1回复 待解决
HarmonyOS ArkTS主动H5通信方式是什么
1771浏览 • 1回复 待解决
HarmonyOS web原生H5如何交互?
1771浏览 • 1回复 待解决
HarmonyOS h5HarmonyOS怎么通信
914浏览 • 1回复 待解决
HarmonyOS H5调用原生扫码功能
1337浏览 • 1回复 待解决
HarmonyOS webH5交互
1937浏览 • 1回复 待解决
HarmonyOS h5原生交互、页面状态机
1065浏览 • 1回复 待解决
H5原生调JSbrige的demo示例
1245浏览 • 1回复 待解决
HarmonyOS 原生H5页面交互
1004浏览 • 1回复 待解决
HarmonyOS H5打开原生相机
1073浏览 • 1回复 待解决