HarmonyOS鸿蒙Next中web h5加载问题(注册对象给H5包含方法列表,H5无法加载)

HarmonyOS鸿蒙Next中web h5加载问题(注册对象给H5包含方法列表,H5无法加载)

web 在加载指定的页面,添加js回调, 使用指定的name,如果方法列表是空的,页面可以加载出来,方法列表不为空就不行

可以加载出来 .javaScriptProxy({ object: this.testObj, name: “syjs”, methodList: [], controller: this.controller })

不可以加载出来 .javaScriptProxy({ object: this.testObj, name: “syjs”, methodList: [“test”], controller: this.controller })

完整代码:

Web({
  src: this.loadUrl, 
  controller: this.controller 
})//设置是否允许执行JavaScript脚本,默认允许执行。
.javaScriptAccess(true)//设置是否开启文档对象模型存储接口(DOM Storage API)权限,默认未开启。
.domStorageAccess(true)
.javaScriptProxy({
  object: this.testObj,
  name: "syjs",
  methodList: ["test"],
  controller: this.controller
})

更多关于HarmonyOS鸿蒙Next中web h5加载问题(注册对象给H5包含方法列表,H5无法加载)的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

javaScriptProxy中的name和h5页本身windows的对象冲突,源web页也有一个全局的syjs对象,换个名字就行,参考:

import { webview } from '@kit.ArkWeb';

class testClass {
  constructor() {
  }

  test(): string {
    return 'ArkTS Hello World!';
  }
}
@Entry
@Component
struct WebPage {
  @State message: string = 'Hello World';
  @State loadUrl: string = "https://caiyifu-h5-jiaofu.qianziworth.cn/partner/home";
  controller: webview.WebviewController = new webview.WebviewController();
  // 声明需要注册的对象
  @State testObj: testClass = new testClass();
  build() {
    Column() {
      Text(this.loadUrl)
        .id('WebPageHelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .copyOption(CopyOptions.LocalDevice)

      Web({ src: this.loadUrl, controller: this.controller })//设置是否允许执行JavaScript脚本,默认允许执行。
        .javaScriptAccess(true)//设置是否开启文档对象模型存储接口(DOM Storage API)权限,默认未开启。
        .domStorageAccess(true)
        .javaScriptProxy({
          object: this.testObj,
          name: "testObj",
          methodList: ["test"],
          controller: this.controller
        }).id('Web')
    }
    .height('100%')
    .width('100%')
  }
}

注:syjs这个是原来如果是用在android里的key,得适配下 。可以用devTools验证,加syjs的话,web那边windows中syjs就是有一个test函数,但是本身h5页面又很多关于window.syjs的代码,可能是前端需要的syjs中的某些方法没有提供导致的。

参考文档: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/web-debugging-with-devtools-V5

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-basic-components-web-V5#javascriptproxy12

更多关于HarmonyOS鸿蒙Next中web h5加载问题(注册对象给H5包含方法列表,H5无法加载)的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,若H5无法加载注册的对象或方法列表,可能原因包括:

  1. 注册对象未正确初始化或绑定;

  2. H5页面未正确调用注册的方法;

  3. 跨域问题导致通信失败。

建议检查以下步骤:

  • 确保在WebView中正确初始化并注册对象;
  • 验证H5页面调用代码;
  • 检查是否有跨域限制,必要时配置WebView的跨域权限。

若问题依旧,调试日志以定位具体错误。

回到顶部