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

简介: 本教程介绍如何在HarmonyOS中使用Web组件加载本地页面和资源,通过实战示例展示如何优化应用启动体验、实现页面跳转及动态加载HTML内容,适用于教育和开发学习场景。

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

参考资料:
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/web-page-loading-with-web-components#%E5%8A%A0%E8%BD%BD%E6%9C%AC%E5%9C%B0%E9%A1%B5%E9%9D%A2

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

在下面的示例中展示加载本地页面文件的方法:
将本地页面文件放在应用的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 })
    }
  }
}
目录
相关文章
|
4月前
|
容器
HarmonyOS NEXT仓颉开发语言实战案例:外卖App
仓颉语言实战分享,教你如何用仓颉开发外卖App界面。内容包括页面布局、导航栏自定义、搜索框实现、列表模块构建等,附完整代码示例。轻松掌握Scroll、List等组件使用技巧,提升HarmonyOS应用开发能力。
|
3月前
|
移动开发 前端开发 JavaScript
鸿蒙NEXT时代你所不知道的全平台跨端框架:CMP、Kuikly、Lynx、uni-app x等
本篇基于当前各大活跃的跨端框架的现状,对比当前它们的情况和未来的可能,帮助你在选择框架时更好理解它们的特点和差异。
312 0
|
4月前
|
安全 API 开发工具
【HarmonyOS NEXT】一键扫码功能
这些Kit为我们应用开发提升了极大地效率。很多简单的功能,如果不需要太深的定制化需求,直接调用kit提供的API就可以实现,在android或者ios上需要很多代码才能实现的功能效果。
119 0
HarmonyOS NEXT仓颉开发语言实战案例:电影App
周末好!本文分享使用仓颉语言重构ArkTS实现的电影App案例,对比两者在UI布局、组件写法及语法差异。内容包括页面结构、列表分组、分类切换与电影展示等。通过代码演示仓颉在HarmonyOS开发中的应用。##仓颉##ArkTS##HarmonyOS开发
|
4月前
|
容器
HarmonyOS NEXT仓颉开发语言实战案例:健身App
本期分享一个健身App首页的布局实现,顶部采用Stack容器实现重叠背景与偏移效果,列表部分使用List结合Scroll实现可滚动内容。代码结构清晰,适合学习HarmonyOS布局技巧。
HarmonyOS NEXT仓颉开发语言实战案例:小而美的旅行App
本文分享了一个旅行App首页的设计与实现,使用List容器搭配Row、Column布局完成个人信息、功能列表及推荐模块的排版,详细展示了HarmonyOS下的界面构建技巧。
|
18天前
|
存储 缓存 5G
鸿蒙 HarmonyOS NEXT端云一体化开发-云存储篇
本文介绍用户登录后获取昵称、头像的方法,包括通过云端API和AppStorage两种方式,并实现上传头像至云存储及更新用户信息。同时解决图片缓存问题,添加上传进度提示,支持自动登录判断,提升用户体验。
90 0
|
18天前
|
存储 负载均衡 数据库
鸿蒙 HarmonyOS NEXT端云一体化开发-云函数篇
本文介绍基于华为AGC的端云一体化开发流程,涵盖项目创建、云函数开通、应用配置及DevEco集成。重点讲解云函数的编写、部署、调用与传参,并涉及环境变量设置、负载均衡、重试机制与熔断策略等高阶特性,助力开发者高效构建稳定云端服务。
178 0
鸿蒙 HarmonyOS NEXT端云一体化开发-云函数篇
|
18天前
|
存储 JSON 数据建模
鸿蒙 HarmonyOS NEXT端云一体化开发-云数据库篇
云数据库采用存储区、对象类型、对象三级结构,支持灵活的数据建模与权限管理,可通过AGC平台或本地项目初始化,实现数据的增删改查及端侧高效调用。
50 0
|
18天前
|
存储 开发者 容器
鸿蒙 HarmonyOS NEXT星河版APP应用开发-ArkTS面向对象及组件化UI开发使用实例
本文介绍了ArkTS语言中的Class类、泛型、接口、模块化、自定义组件及状态管理等核心概念,并结合代码示例讲解了对象属性、构造方法、继承、静态成员、访问修饰符等内容,同时涵盖了路由管理、生命周期和Stage模型等应用开发关键知识点。
150 0
鸿蒙 HarmonyOS NEXT星河版APP应用开发-ArkTS面向对象及组件化UI开发使用实例