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消息通信
450浏览 • 1回复 待解决
HarmonyOS ArkTSH5交互方法
533浏览 • 1回复 待解决
h5应用端的sdk通信问题
760浏览 • 1回复 待解决
HarmonyOS H5原生交互
572浏览 • 1回复 待解决
HarmonyOS h5和ArkTS通信
728浏览 • 1回复 待解决
HarmonyOS h5 window.history 无效
426浏览 • 1回复 待解决
HarmonyOS ArkTS主动H5通信方式是什么
1049浏览 • 0回复 待解决
HarmonyOS web原生H5如何交互?
1115浏览 • 1回复 待解决
HarmonyOS h5HarmonyOS怎么通信
417浏览 • 1回复 待解决
HarmonyOS H5调用原生扫码功能
520浏览 • 1回复 待解决
HarmonyOS webH5交互
1241浏览 • 1回复 待解决
HarmonyOS h5原生交互、页面状态机
450浏览 • 1回复 待解决
H5原生调JSbrige的demo示例
678浏览 • 1回复 待解决
HarmonyOS 原生H5页面交互
380浏览 • 1回复 待解决
HarmonyOS H5打开原生相机
456浏览 • 1回复 待解决
HarmonyOS webview原生通信
560浏览 • 1回复 待解决
HarmonyOS H5和app通信是否有传输上限
208浏览 • 1回复 待解决