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): void
加载指定的 url,headers 为可选的请求头。
3)loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void
加载指定的数据。
3. Web 组件加载网页示例
本示例演示加载网页的四种方式,默认是加载资源文件,运行后的初始界面如下所示:
下面详细介绍创建该应用的步骤。
步骤 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@Componentstruct 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[0]
} }).catch((err) => { console.error(err.message) }); }
//加载本地文件 async loadLocalFile() { let context = getContext(this) let segments = this.loadFileUri.split('/') //文件名称 let fileName = segments[segments.length-1] + ".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 的效果,然后输入在线网站,比如百度的首页,随后单击“加载”按钮,截图如下所示:
这样就演示了加载在线网址的效果。
步骤 7:单击“选择”按钮,弹出文件选择窗口,如图所示:
可以选择 demo.html,该文件内容如下:
<!-- index.html --><!DOCTYPE html><html>
<body> <div style="text-align: center;">测试加载本地文件</div> <div style="text-align: center;">通过复制本地文件到沙箱实现</div></body>
</html>
复制代码
然后单击“选择”按钮后的“加载”按钮,把选中的文件复制到沙箱中,最后加载这个文件,效果如下所示:
步骤 8:最后是直接加载网页内容,在输入框里输入要加载的 html,然后单击“加载”按钮,效果如图所示:
这样就完成了 Web 组件加载网页的应用。
4. 加载功能分析
这四种加载方式中,最复杂的是加载从本机选择的文件,因为文件不在沙箱中,无法直接加载,所以首先把选中的文件复制到沙箱中,然后再从沙箱中加载该文件,实现的代码如下:
//加载本地文件 async loadLocalFile() { let context = getContext(this) let segments = this.loadFileUri.split('/') //文件名称 let fileName = segments[segments.length-1] + ".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://gitee.com/zl3624/harmonyos_network_samples/tree/master/code/web/WebDemo
本系列源码地址:
https://gitee.com/zl3624/harmonyos_network_samples
评论