鼠扑 发表于 2024-12-16 22:18:18

鸿蒙开发系列(HarmonyOS)Web组件及加载网页示例

鸿蒙NEXT开发实战往期必看文章:
一分钟了解”纯血版!鸿蒙HarmonyOS Next应用开发!
“非常详细的” 鸿蒙HarmonyOS Next应用开发学习门路!(从零基础入门到醒目)
HarmonyOS NEXT应用开发案例实践总结合(持续更新......)
HarmonyOS NEXT应用开发性能优化实践总结(持续更新......)
1. Web组件简介

在应用界面里嵌入网页是很多快速APP开发使用的方式之一,通过这种方式可以比力好的达到多端兼容的效果,鸿蒙也一样提供了类似的能力,就是基础组件中的Web组件。当然,单纯的靠Web组件也无法实现复杂的功能,还需要对应的控制器WebviewController,两者配合可以达到最佳的控制和显示效果。
2. Web组件及控制器常用方法

web组件及其控制器位于web_webview模块下,使用如下的方式导入:
import web_webview from '@ohos.web.webview'; web_webview模块包罗了众多的操纵方法,就本文而言,重点需要掌握的是如下三个:
Web组件方法
1)Web(options: { src: ResourceStr, controller: WebviewController | WebController})
创建Web组件实例,此中src是网页资源地点,controller是组件控制器,从API Version 9开始,发起使用WebviewController作为控制器。
WebviewController方法
2)loadUrl(url: string | Resource, headers?: Array<WebHeader>): void
加载指定的url,headers为可选的请求头。
3)loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void
加载指定的数据。
3. Web组件加载网页示例

本示例演示加载网页的四种方式,默认是加载资源文件,运行后的初始界面如下所示:

https://i-blog.csdnimg.cn/img_convert/54894b196b7e72a2927798260499f66e.jpeg
下面详细先容创建该应用的步骤。
步骤1:创建Empty Ability项目。
步骤2:在module.json5设置文件加上对权限的声明:
"requestPermissions": [
      {
      "name": "ohos.permission.INTERNET"
      }
    ] 这里添加了获取互联网信息的权限。
步骤3:在Index.ets文件里添加如下的代码:
import http from '@ohos.net.http';
import util from '@ohos.util';
import fs from '@ohos.file.fs';
import picker from '@ohos.file.picker';
import systemDateTime from '@ohos.systemDateTime';
import request from '@ohos.request';
import connection from '@ohos.net.connection';
import HashSet from '@ohos.util.HashSet';
import ArrayList from '@ohos.util.ArrayList';
import web_webview from '@ohos.web.webview'

@Entry
@Component
struct Index {
//要加载的网址
@State webUrl: string = "https://www.baidu.com"
//要加载的文件
@State loadFileUri: string = ""
//要加载的内容
@State webContent: string = `<!DOCTYPE html>
<html>
<body style="font-size: large;text-align: center;">
<div>测试加载文本内容!</div>
</body>
</html>`
scroller: Scroller = new Scroller()
contentScroller: Scroller = new Scroller()
controller: web_webview.WebviewController = new web_webview.WebviewController()

build() {
    Row() {
      Column() {
      Text("Web加载示例")
          .fontSize(14)
          .fontWeight(FontWeight.Bold)
          .width('100%')
          .textAlign(TextAlign.Center)
          .padding(10)

      Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
          Text("网址:")
            .fontSize(14)
            .width(50)
            .flexGrow(0)

          TextInput({ text: this.webUrl })
            .onChange((value) => {
            this.webUrl = value
            })
            .width(110)
            .fontSize(11)
            .flexGrow(1)

          Button("加载")
            .onClick(() => {
            this.controller.loadUrl(this.webUrl);
            })
            .width(60)
            .fontSize(14)
            .flexGrow(0)
      }
      .width('100%')
      .padding(5)

      Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
          Text("文件:")
            .fontSize(14)
            .width(50)
            .flexGrow(0)

          TextInput({ text: this.loadFileUri })
            .onChange((value) => {
            this.loadFileUri = value
            })
            .width(110)
            .fontSize(11)
            .flexGrow(1)

          Button("选择")
            .onClick(() => {
            this.selectFile()
            })
            .width(60)
            .fontSize(14)
            .flexGrow(0)
          Button("加载")
            .onClick(() => {
            this.loadLocalFile()
            })
            .width(60)
            .fontSize(14)
            .flexGrow(0)
      }
      .width('100%')
      .padding(5)

      Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
          Text("下方输入框的文本内容:")
            .fontSize(14)
            .width(200)
            .flexGrow(0)
          Button("加载")
            .onClick(() => {
            this.controller.loadData(this.webContent, "text/html",
                "UTF-8")
            })
            .width(60)
            .fontSize(14)
            .flexGrow(0)
      }
      .width('100%')
      .padding(5)

      Scroll(this.contentScroller) {
          TextArea({ text: this.webContent })
            .onChange((value) => {
            this.webContent = value
            })
            .backgroundColor(0xffffee)
            .width('100%')
            .fontSize(11)
      }
      .align(Alignment.Top)
      .backgroundColor(0xeeeeee)
      .height(120)
      .scrollable(ScrollDirection.Vertical)
      .scrollBar(BarState.On)
      .scrollBarWidth(20)

      Scroll(this.scroller) {
          Web({ src: $rawfile("index.html"), controller: this.controller })
            .padding(10)
            .width('100%')
            .backgroundColor(0xeeeeee)
      }
      .align(Alignment.Top)
      .backgroundColor(0xeeeeee)
      .height(300)
      .flexGrow(1)
      .scrollable(ScrollDirection.Vertical)
      .scrollBar(BarState.On)
      .scrollBarWidth(20)
      }
      .width('100%')
      .justifyContent(FlexAlign.Start)
      .height('100%')
    }
    .height('100%')

}

//选择文件,为简单起见,选择一个不太大的网页文件
selectFile() {
    let documentPicker = new picker.DocumentViewPicker();
    documentPicker.select().then((result) => {
      if (result.length > 0) {
      this.loadFileUri = result

      }
    }).catch((err) => {
      console.error(err.message)
    });
}

//加载本地文件
async loadLocalFile() {
    let context = getContext(this)
    let segments = this.loadFileUri.split('/')
    //文件名称
    let fileName = segments + ".html"

    //计划复制到的目标路径
    let realUri = context.cacheDir + "/" + fileName

    //复制选择的文件到沙箱cache文件夹
    try {
      let file = await fs.open(this.loadFileUri);
      fs.copyFileSync(file.fd, realUri)
      this.controller.loadUrl(`file://${realUri}`);
    } catch (err) {
      console.error(err.message)
    }
}
} 步骤4:添加资源文件index.html,路径为src/main/resources/rawfile/index.html,内容如下:
<!-- index.html -->
<!DOCTYPE html>
<html>

<body style="font-size: large;text-align: center;">
<div>Hello HarmonyOS Next</div>
<div>Load with resource file</div>
</body>

</html> 步骤5:编译运行,可以使用模拟器大概真机。
步骤6:如前所示,默认页面是加载资源文件index.html的效果,然后输入在线网站,比如百度的首页,随后单击“加载”按钮,截图如下所示:

https://i-blog.csdnimg.cn/img_convert/0ea117154e12e9d66dde3316f028c6a0.jpeg
如许就演示了加载在线网址的效果。
步骤7:单击“选择”按钮,弹出文件选择窗口,如图所示:

https://i-blog.csdnimg.cn/img_convert/0822ff454c79d14278cf35f3cae3d465.jpeg
可以选择demo.html,该文件内容如下:
<!-- index.html -->
<!DOCTYPE html>
<html>

<body>
    <div style="text-align: center;">测试加载本地文件</div>
    <div style="text-align: center;">通过复制本地文件到沙箱实现</div>
</body>

</html> 然后单击“选择”按钮后的“加载”按钮,把选中的文件复制到沙箱中,最后加载这个文件,效果如下所示:

https://i-blog.csdnimg.cn/img_convert/a0365d4a0152900bfa33ec002efcc274.jpeg
步骤8:最后是直接加载网页内容,在输入框里输入要加载的html,然后单击“加载”按钮,效果如图所示:

https://i-blog.csdnimg.cn/img_convert/331bee0ab0b228da3aa8efc078792dd2.jpeg
如许就完成了Web组件加载网页的应用。
4. 加载功能分析

这四种加载方式中,最复杂的是加载从本机选择的文件,因为文件不在沙箱中,无法直接加载,所以起首把选中的文件复制到沙箱中,然后再从沙箱中加载该文件,实现的代码如下:
//加载本地文件
async loadLocalFile() {
    let context = getContext(this)
    let segments = this.loadFileUri.split('/')
    //文件名称
    let fileName = segments + ".html"

    //计划复制到的目标路径
    let realUri = context.cacheDir + "/" + fileName

    //复制选择的文件到沙箱cache文件夹
    try {
      let file = await fs.open(this.loadFileUri);
      fs.copyFileSync(file.fd, realUri)
      this.controller.loadUrl(`file://${realUri}`);
    } catch (err) {
      console.error(err.message)
    }
} https://i-blog.csdnimg.cn/direct/879cf7fbe02943fc85afbf02adea8104.png

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 鸿蒙开发系列(HarmonyOS)Web组件及加载网页示例