HarmonyOS鸿蒙Next中Web组件H5部分功能异常问题定位及解决

HarmonyOS鸿蒙Next中Web组件H5部分功能异常问题定位及解决

【问题现象】

Web组件显示一个有搜索功能的H5页面,搜索框内输入关键词后点击键盘上的完成按钮显示空白、不能够正常搜索, 但是同样的页面在HarmonyOS系统浏览器中打开该H5页面,搜索功能是正常的。问题现象截图:

点击放大

代码如下:

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

@Entry
@Component
struct Index {
  webController: WebviewController = new webview.WebviewController();

  build() {
    Column() {
      Web({
        src: 'https://www.chinastory.cn/wap-news/search/index.html',
        controller: this.webController
      })
    }
  }
}

【背景知识】

1. ArkWeb

ArkWeb(方舟Web)提供了Web组件,用于在应用程序中显示Web页面内容。

2. Web调试

Web组件支持使用DevTools工具调试前端页面。DevTools是一个 Web前端开发调试工具,提供了电脑上调试移动设备前端页面的能力。开发者通过setWebDebuggingAccess()接口开启Web组件前端页面调试能力,利用DevTools工具可以在电脑上调试移动设备上的前端网页,设备需为4.1.0及以上版本。

【定位思路】

使用DevTools工具调试前端页面。点击键盘上的完成/开始按钮触发搜索时,可以看到前端页面有报错信息,截图如下:

点击放大

根据错误堆栈,点击at wn.searchLocalStorage (index.html?q=%E4%B8%A4%E4%BC%9A:431:46)这行的index.html链接进入报错点内,可以发现是localStorage.getItem()出错了,而错误为“Cannot read properties of null (reading ‘getItem’)”——localStorage对象的值为null?看来问题出在domStorage( localStorage+sessionStorage)上。而Web组件有一个属性叫domStorageAccess——设置是否开启文档对象模型存储接口(DOM Storage API)权限,默认未开启。

点击放大

【解决方案】

将Web组件的domStorageAccess该属性设置为true即可。

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

@Entry
@Component
struct Index {
  webController: WebviewController = new webview.WebviewController();

  build() {
    Column() {
      Web({
        src: 'https://www.chinastory.cn/wap-news/search/index.html',
        controller: this.webController
      })
        .domStorageAccess(true)
    }
  }
}

【总结】

Web组件有一系列涉及权限控制的属性,其中有五个属性是默认未开启的(API 12),需要根据H5的使用情况主动设置开启:

  • fileAccess——设置是否开启应用中文件系统的访问。$rawfile(filepath/filename)中rawfile路径的文件不受该属性影响而限制访问。从API 12开始,默认未开启。
  • domStorageAccess——设置是否开启文档对象模型存储接口(DOM Storage API)权限,默认未开启。
  • databaseAccess——设置是否开启数据库存储API权限,默认不开启。
  • multiWindowAccess——设置是否开启多窗口权限,默认不开启。
  • forceDarkAccess——设置网页是否开启强制深色模式。默认关闭。该属性仅在darkMode开启深色模式时生效。

更多关于HarmonyOS鸿蒙Next中Web组件H5部分功能异常问题定位及解决的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中Web组件H5部分功能异常问题定位及解决的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


问题定位

Web组件显示H5页面时,搜索功能异常,点击完成按钮后页面空白,原因是domStorageAccess属性默认未开启,导致localStorage无法正常使用。

解决方案

在Web组件中设置domStorageAccess属性为true,开启文档对象模型存储接口权限。代码如下:

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

@Entry
@Component
struct Index {
  webController: WebviewController = new webview.WebviewController();

  build() {
    Column() {
      Web({
        src: 'https://www.chinastory.cn/wap-news/search/index.html',
        controller: this.webController
      })
        .domStorageAccess(true)
    }
  }
}
回到顶部