HarmonyOS webview加载html片段,是否有相关的api设置宽度的自适应?

HarmonyOS webview加载html片段,是否有相关的api设置宽度的自适应?

阅读 496
1 个回答

解决思路供参考:

1.前端js写一个函数在页面加载完毕之后获取html的高度。

2.ArkTS调用h5函数的能力,调用该函数并接受到html的高度

3.利用web组件的生命周期回调函数onpageend中设置接收到的h5侧传来的html的宽高,并进行设置达到自适应

需要注意单位转换,h5获取的高度是px,ArkTS端的设置可以根据你自己喜欢的单位进行设置

参考demo:

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
              console.info("pageheight="+this.webResult);
            }
          );
        })
        .height(parseInt(this.webResult))
    }
  }
}

index.html文件:

<script type="text/javascript">
  function watchWindowSize(){
    var h = document.body.clientHeight;
    return h;
  }
  </script>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进