HarmonyOS鸿蒙Next中如何处理获取到的Web组件尺寸与实际渲染尺寸不一致问题

HarmonyOS鸿蒙Next中如何处理获取到的Web组件尺寸与实际渲染尺寸不一致问题

【问题现象】

Web组件加载H5页面后,通过getPageHeight获取到宽高和实际渲染内容的宽高不一致。

如下图:伙伴想要Web组件渲染的网页内容的高度,而不是Web组件的高度。

点击放大

【背景知识】

  • @ohos.web.webview提供Web控制能力,Web组件提供网页显示的能力。
  • WebView组件高度获取,是通过:WebviewController的getPageHeight方法。

【解决方案】

  1. Web组件高度可通过getPageHeight获取,但是这个获取的是Web组件的宽高,实际内容高度可以使用前端js脚本document.querySelector('body').offsetHeight获取。
  2. 在前端网页加上<html><meta name="viewport" content="width=device-width, initial-scale=1.0">,vp和px大致为1:1。
import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController();
  @State webResult: string = ''

  build() {
    Column() {
      Text(this.webResult).fontSize(20)
      Web({
        src: $rawfile('index.html'),
        controller: this.controller
      })
        .javaScriptAccess(true)
        .aspectRatio(1.5)
        .onPageEnd(e => {
          this.controller.runJavaScript(
            'watchWindowSize()',
            (error, result) => {
              this.webResult = result
              let pageHeight = this.controller.getPageHeight() + "";
              console.info("pageHeight =" + pageHeight);
              pageHeight = this.webResult;
              console.info("webResult =" + this.webResult);
            }
          )
        })
    }
  }
}
  1. index.html 中提供watchWindowSize方法,返回body高度。
<!--fit_content.html-->
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <title>Fit-Content</title>
</head>

<script>
    function watchWindowSize() {
          return document.querySelector('body').offsetHeight;
     }
</script>
<body>
<div>
    <div><h2 id="使用场景">使用场景</h2>
        <p>ArkWeb(方舟Web)提供了Web组件,用于在应用程序中显示Web页面内容。常见使用场景包括:</p>
        <ul>
            <li>
              <p>应用集成Web页面:应用可以在页面中使用Web组件,嵌入Web页面内容,以降低开发成本,提升开发、运营效率。</p>
            </li>
        </ul>
    </div>
</div>
</body>
</html>
  1. 结果:
  • webResult:Web组件高度。
  • pageHeight:html body 高度。

点击放大

使用ArkUI Inspector检查Web高度,与打印结果一致。

点击放大

使用前端工具Devtools查看网页实际高度,与打印结果一致。

点击放大


更多关于HarmonyOS鸿蒙Next中如何处理获取到的Web组件尺寸与实际渲染尺寸不一致问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中如何处理获取到的Web组件尺寸与实际渲染尺寸不一致问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


使用 document.querySelector('body').offsetHeight 获取实际渲染内容高度。

在前端网页中添加 <meta name="viewport" content="width=device-width, initial-scale=1.0">,确保 vppx 比例为 1:1。

通过 runJavaScript 调用前端 watchWindowSize 方法返回 body 高度。

回到顶部