HarmonyOS NEXT实战:加载本地网页资源

举报
鸿蒙开发工程师 发表于 2025/06/28 15:39:25 2025/06/28
【摘要】 ##HarmonyOS Next实战##HarmonyOS SDK应用服务##教育##参考资料:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/web-page-loading-with-web-components#加载本地页面为了在启动、跳转、弱网等场景下减少用户等待感知,同时为动态内容加载争取时间,可以加载本地...

##HarmonyOS Next实战##HarmonyOS SDK应用服务##教育##

参考资料:
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/web-page-loading-with-web-components#加载本地页面

为了在启动、跳转、弱网等场景下减少用户等待感知,同时为动态内容加载争取时间,可以加载本地页面优化用户体验。

在下面的示例中展示加载本地页面文件的方法:
将本地页面文件放在应用的rawfile目录下,开发者可以在Web组件创建的时候指定默认加载的本地页面,并且加载完成后可通过调用loadUrl()接口变更当前Web组件的页面。

加载本地html文件时引用本地css样式文件可以通过以下方法实现。

<link rel="stylesheet" href="resource://rawfile/xxx.css">
<link rel="stylesheet" href="file:///data/storage/el2/base/haps/entry/cache/xxx.css">// 加载沙箱路径下的本地css文件。

加载 $r 或 $rawfile 本地页面

在resources/rawfile目录下
新增hello.html

<!DOCTYPE html>
<html>
  <body>
    <h1>Hello!</h1>
  </body>
</html>

新增helloAgain.html

<!DOCTYPE html>
<html>
  <body>
    <h1>Hello again!</h1>
  </body>
</html>

新增WebLocalPage

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

@Entry
@Component
struct WebLocalPage {
  src: ResourceStr = $rawfile("hello.html")
  webController: webview.WebviewController = new webview.WebviewController();

  build() {
    Column({ space: 10 }) {
      Text('WebPage')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
      Row({ space: 10 }){
        Button('hello')
          .onClick(() => {
            try {
              // 点击按钮时,通过loadUrl,跳转到hello.html
              this.webController.loadUrl( $rawfile("hello.html"));
            } catch (error) {
              console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
            }
          })
        Button('hello again')
          .onClick(() => {
            try {
              // 点击按钮时,通过loadUrl,跳转到helloAgain.html
              this.webController.loadUrl( $rawfile("helloAgain.html"));
            } catch (error) {
              console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
            }
          })
      }

      Web({ src: this.src, controller: this.webController })
        .width('100%')
        .layoutWeight(1)
        .horizontalScrollBarAccess(false)//设置是否显示横向滚动条
        .verticalScrollBarAccess(false) //设置是否显示纵向滚动条
    }
    .height('100%')
    .width('100%')
  }
}

通过 resource协议加载本地资源

将$rawfile替换为resource协议

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

@Entry
@Component
struct WebLocalPage {
  // src: ResourceStr = $rawfile("hello.html")
  src: ResourceStr = 'resource://rawfile/hello.html'
  webController: webview.WebviewController = new webview.WebviewController();

  build() {
    Column({ space: 10 }) {
      Text('WebPage')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
      Row({ space: 10 }) {
        Button('hello')
          .onClick(() => {
            try {
              // 点击按钮时,通过loadUrl,跳转到hello.html
              // this.webController.loadUrl($rawfile("hello.html"));
              this.webController.loadUrl('resource://rawfile/hello.html');
            } catch (error) {
              console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
            }
          })
        Button('hello again')
          .onClick(() => {
            try {
              // 点击按钮时,通过loadUrl,跳转到helloAgain.html
              // this.webController.loadUrl($rawfile("helloAgain.html"));
              this.webController.loadUrl('resource://rawfile/helloAgain.html');
            } catch (error) {
              console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
            }
          })
      }

      Web({ src: this.src, controller: this.webController })
        .width('100%')
        .layoutWeight(1)
        .horizontalScrollBarAccess(false)//设置是否显示横向滚动条
        .verticalScrollBarAccess(false) //设置是否显示纵向滚动条
    }
    .height('100%')
    .width('100%')
  }
}

加载HTML格式的文本数据

Web组件的src可直接加载HTML字符串。

// WebComponent.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController();
  htmlStr: string = "data:text/html, <html><body bgcolor=\"green\"><h1>Source:<pre>source</pre></h1></body></html>";

  build() {
    Column() {
      // 组件创建时,加载htmlStr
      Web({ src: this.htmlStr, controller: this.controller })
    }
  }
}

Web组件可以通过loadData()接口实现加载HTML格式的文本数据。当开发者不需要加载整个页面,只需要显示一些页面片段时,可通过此功能来快速加载页面,当加载大量html文件时,需设置第四个参数baseUrl为"data"。

// WebComponent.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController();

  build() {
    Column() {
      Button('loadData')
        .onClick(() => {
          try {
            // 点击按钮时,通过loadData,加载HTML格式的文本数据
            this.controller.loadData(
              "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>",
              "text/html",
              "UTF-8"
            );
          } catch (error) {
            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
          }
        })
      // 组件创建时,加载www.example.com
      Web({ src: 'www.example.com', controller: this.controller })
    }
  }
}
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。