【鸿蒙开发】第十七章 Web组件(一)

1 Web概述

Web组件用于在应用程序中显示Web页面内容,为开发者提供页面加载页面交互页面调试等能力。

  • 页面加载:Web组件提供基础的前端页面加载的能力,包括:加载网络页面、本地页面、html格式文本数据

  • 页面交互:Web组件提供丰富的页面交互的方式,包括:设置前端页面深色模式,新窗口中加载页面,位置权限管理,Cookie管理,应用侧使用前端页面JavaScript等能力

  • 页面调试:Web组件支持使用Devtools工具调试前端页面

2 Web使用

页面加载是Web组件的基本功能。根据页面加载数据来源可以分为三种常用场景,包括加载网络页面加载本地页面加载HTML格式的富文本数据
页面加载过程中,若涉及网络资源获取,需要配置ohos.permission.INTERNET网络访问权限。

2.1 加载网络页面

可以在Web组件创建时,指定默认加载的网络页面 。在默认页面加载完成后,如果需要变更此Web组件显示的网络页面,可以通过调用loadUrl()接口加载指定的网页。

在下面的示例中,在Web组件加载完“www.example.com”页面后,可通过loadUrl接口将此Web组件显示页面变更为“www.example1.com”

// xxx.ets
import web_webview from '@ohos.web.webview';
import business_error from '@ohos.base';@Entry
@Component
struct WebComponent {webviewController: web_webview.WebviewController = new web_webview.WebviewController();build() {Column() {Button('loadUrl').onClick(() => {try {// 点击按钮时,通过loadUrl,跳转到www.example1.comthis.webviewController.loadUrl('www.example1.com');} catch (error) {let e: business_error.BusinessError = error as business_error.BusinessError;console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);}})// 组件创建时,加载www.example.comWeb({ src: 'www.example.com', controller: this.webviewController})}}
}

2.2 加载本地页面

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

在下面的示例中展示加载本地页面文件的方法:

  1. 将资源文件放置在应用的resources/rawfile目录下。在这里插入图片描述
  2. 应用侧代码
// xxx.ets
import web_webview from '@ohos.web.webview';
import business_error from '@ohos.base';@Entry
@Component
struct WebComponent {webviewController: web_webview.WebviewController = new web_webview.WebviewController();build() {Column() {Button('loadUrl').onClick(() => {try {// 点击按钮时,通过loadUrl,跳转到local1.htmlthis.webviewController.loadUrl($rawfile("local1.html"));} catch (error) {let e: business_error.BusinessError = error as business_error.BusinessError;console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);}})// 组件创建时,通过$rawfile加载本地文件local.htmlWeb({ src: $rawfile("local.html"), controller: this.webviewController })}}
}
  1. local.html页面代码。
<!-- local.html -->
<!DOCTYPE html>
<html><body><p>Hello World</p></body>
</html>

2.3 加载HTML格式的文本数据

Web组件可以通过loadData()接口实现加载HTML格式的文本数据。当不需要加载整个页面,只需要显示一些页面片段时,可通过此功能来快速加载页面。

// xxx.ets
import web_webview from '@ohos.web.webview';
import business_error from '@ohos.base';@Entry
@Component
struct WebComponent {controller: web_webview.WebviewController = new web_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) {let e: business_error.BusinessError = error as business_error.BusinessError;console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);}})// 组件创建时,加载www.example.comWeb({ src: 'www.example.com', controller: this.controller })}}
}

3 Web基本属性与事件

3.1 设置深色模式

Web组件支持对前端页面进行深色模式配置
通过darkMode()接口可以配置不同的深色模式,WebDarkMode.Off模式表示关闭深色模式。WebDarkMode.On表示开启深色模式,并且深色模式跟随前端页面。WebDarkMode.Auto表示开启深色模式,并且深色模式跟随系统。 在下面的示例中, 通过darkMode()接口将页面深色模式配置为跟随系统。

// xxx.ets
import web_webview from '@ohos.web.webview';@Entry
@Component
struct WebComponent {controller: web_webview.WebviewController = new web_webview.WebviewController();@State mode: WebDarkMode = WebDarkMode.Auto;build() {Column() {Web({ src: 'www.example.com', controller: this.controller }).darkMode(this.mode)}}
}

通过forceDarkAccess()接口可将前端页面强制配置深色模式,且深色模式不跟随前端页面和系统。配置该模式时候,需要将深色模式配置成WebDarkMode.On。 在下面的示例中, 通过forceDarkAccess()接口将页面强制配置为深色模式。

// xxx.ets
import web_webview from '@ohos.web.webview';@Entry		
@Component
struct WebComponent {controller: web_webview.WebviewController = new web_webview.WebviewController();@State mode: WebDarkMode = WebDarkMode.On;@State access: boolean = true;build() {Column() {Web({ src: 'www.example.com', controller: this.controller }).darkMode(this.mode).forceDarkAccess(this.access)}}
}

3.2 上传文件

Web组件支持前端页面选择文件上传功能,应用开发者可以使用onShowFileSelector()接口来处理前端页面文件上传的请求。

下面的示例中,当用户在前端页面点击文件上传按钮,应用侧在onShowFileSelector()接口中收到文件上传请求,在此接口中开发者将上传的本地文件路径设置给前端页面。

  1. 应用侧代码。
// xxx.ets
import web_webview from '@ohos.web.webview';@Entry
@Component
struct WebComponent {controller: web_webview.WebviewController = new web_webview.WebviewController()build() {Column() {// 加载本地local.html页面Web({ src: $rawfile('local.html'), controller: this.controller }).onShowFileSelector((event) => {// 开发者设置要上传的文件路径let fileList: Array<string> = ['xxx/test.png',]if (event) {event.result.handleFileList(fileList)}return true;})}}
}
  1. local.html页面代码。
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Document</title>
</head><body>
<!-- 点击上传文件按钮 -->
<input type="file" value="file"></br>
</body>
</html>

3.3 在新窗口中打开页面

Web组件提供了在新窗口打开页面的能力,开发者可以通过multiWindowAccess()接口来设置是否允许网页在新窗口打开。当有新窗口打开时,应用侧会在onWindowNew()接口中收到Web组件新窗口事件,开发者需要在此接口事件中,新建窗口来处理Web组件窗口请求。

  • 说明:
    allowWindowOpenMethod()接口设置为true时,前端页面通过JavaScript函数调用的方式打开新窗口。
    如果开发者在onWindowNew()接口通知中不需要打开新窗口,需要将ControllerHandler.setWebController()接口返回值设置成null

如下面的本地示例,当用户点击“新窗口中打开网页”按钮时,应用侧会在onWindowNew()接口中收到Web组件新窗口事件。

  1. 应用侧代码。
// xxx.ets
import web_webview from '@ohos.web.webview'//在同一page页有两个web组件。在WebComponent新开窗口时,会跳转到NewWebViewComp。
@CustomDialog
struct NewWebViewComp {
controller?: CustomDialogController
webviewController1: web_webview.WebviewController = new web_webview.WebviewController()
build() {Column() {Web({ src: "", controller: this.webviewController1 }).javaScriptAccess(true).multiWindowAccess(false).onWindowExit(()=> {console.info("NewWebViewComp onWindowExit")if (this.controller) {this.controller.close()}})}}
}@Entry
@Component
struct WebComponent {controller: web_webview.WebviewController = new web_webview.WebviewController()dialogController: CustomDialogController | null = nullbuild() {Column() {Web({ src:$rawfile("window.html"), controller: this.controller }).javaScriptAccess(true)//需要使能multiWindowAccess.multiWindowAccess(true).allowWindowOpenMethod(true).onWindowNew((event) => {if (this.dialogController) {this.dialogController.close()}let popController:web_webview.WebviewController = new web_webview.WebviewController()this.dialogController = new CustomDialogController({builder: NewWebViewComp({webviewController1: popController})})this.dialogController.open()//将新窗口对应WebviewController返回给Web内核。//如果不需要打开新窗口请调用event.handler.setWebController接口设置成null。//若不调用event.handler.setWebController接口,会造成render进程阻塞。event.handler.setWebController(popController)})}}
}
  1. window.html页面代码。
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>WindowEvent</title>
</head>
<body>
<input type="button" value="新窗口中打开网页" onclick="OpenNewWindow()">
<script type="text/javascript">function OpenNewWindow(){let openedWindow = window.open("about:blank", "", "location=no,status=no,scrollvars=no");openedWindow.document.write("<p>这是我的窗口</p>");openedWindow.focus();}
</script>
</body>
</html>

3.4 管理位置权限

Web组件提供位置权限管理能力。开发者可以通过onGeolocationShow()接口对某个网站进行位置权限管理。Web组件根据接口响应结果,决定是否赋予前端页面权限。获取设备位置,需要开发者配置ohos.permission.LOCATION权限,并同时在设备上打开应用的位置权限和控制中心的位置信息。

在下面的示例中,用户点击前端页面"获取位置"按钮,Web组件通过弹窗的形式通知应用侧位置权限请求消息。

  1. 前端页面代码。
<!DOCTYPE html>
<html>
<body>
<p id="locationInfo">位置信息</p>
<button onclick="getLocation()">获取位置</button>
<script>
var locationInfo=document.getElementById("locationInfo");
function getLocation(){if (navigator.geolocation) {<!-- 前端页面访问设备地理位置 -->navigator.geolocation.getCurrentPosition(showPosition);}
}
function showPosition(position){locationInfo.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
  1. 应用代码。
// xxx.ets
import web_webview from '@ohos.web.webview';@Entry
@Component
struct WebComponent {controller: web_webview.WebviewController = new web_webview.WebviewController();build() {Column() {Web({ src:$rawfile('getLocation.html'), controller:this.controller }).geolocationAccess(true).onGeolocationShow((event) => {  // 地理位置权限申请通知AlertDialog.show({title: '位置权限请求',message: '是否允许获取位置信息',primaryButton: {value: 'cancel',action: () => {if (event) {event.geolocation.invoke(event.origin, false, false);   // 不允许此站点地理位置权限请求}}},secondaryButton: {value: 'ok',action: () => {if (event) {event.geolocation.invoke(event.origin, true, false);    // 允许此站点地理位置权限请求}}},cancel: () => {if (event) {event.geolocation.invoke(event.origin, false, false);   // 不允许此站点地理位置权限请求}}})})}}
}

H5与端侧交互、Cookies以及Web调试等我们下一章节继续学习:【鸿蒙开发】第十八章 Web组件(二)

参考文献:
[1]OpenHarmoney应用开发文档

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/525082.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

WebSocket:实现客户端与服务器实时通信的技术

&#x1f90d; 前端开发工程师、技术日更博主、已过CET6 &#x1f368; 阿珊和她的猫_CSDN博客专家、23年度博客之星前端领域TOP1 &#x1f560; 牛客高级专题作者、打造专栏《前端面试必备》 、《2024面试高频手撕题》 &#x1f35a; 蓝桥云课签约作者、上架课程《Vue.js 和 E…

RHCE——二、时间管理器与远程登陆服务

RHCE——二、时间管理器与远程登陆服务 一、chrony服务器1、简介重要性Linux的两个时钟设置日期时间timedatectl命令设置date命令设置 NTPChrony介绍 2、安装与配置安装&#xff1a;Chrony配置文件分析实验1实验2重启报错解决方法 二、远程登录服务 一、chrony服务器 1、简介 …

方法的使用

1.什么是方法(method) 在java中方法就是一个代码片段.。几乎相当于c语言的函数。 2.方法定义 方法跟函数是几乎一样的。所以语法是大差不差的。就多了一点东西。之前我们在c语言里已经很详细讲过了函数。这里就简便的讲一下。 相比c语言函数多了个修饰符 。 现在看下其注意…

浅述字典攻击

一、前言 字典攻击是一种常见的密码破解方法&#xff0c;它使用预先编制的字典文件作为攻击字典&#xff0c;通过尝试猜测密码的方式来破解密码。下面是一个关于字典攻击的博客&#xff0c;希望能够为您了解字典攻击提供帮助。 二、字典攻击概述 字典攻击是一种密码破解方法&…

义乌等保测评公司有哪些?用哪款堡垒机好?

对于义乌&#xff0c;相信大家都听过&#xff0c;也都知道&#xff0c;耳熟能详。这不有义乌小伙伴在问&#xff0c;义乌等保测评公司有哪些&#xff1f;用哪款堡垒机好&#xff1f;今天我们就来简单聊聊。 义乌等保测评公司有哪些&#xff1f; 目前浙江义乌本地暂未有正规等保…

Zynq—AD9238数据采集DDR3缓存千兆以太网发送实验(三)

Zynq—AD9238数据采集DDR3缓存千兆以太网发送实验&#xff08;前导&#xff09; Zynq—AD9238数据采集DDR3缓存千兆以太网发送实验&#xff08;一&#xff09; Zynq—AD9238数据采集DDR3缓存千兆以太网发送实验&#xff08;二&#xff09; 八、板级验证 1.验证内容 通过电脑…

套接字的地址结构,IP地址转换函数,网络编程的接口

目录 一、套接字的地址结构 1.1 通用socket地址结构 1.2 专用socket地址结构 1.2.1 tcp协议族 1.2.3 IP协议族 二、IP地址转换函数 三、网络编程接口 3.1 socket() 3.2 bind() 3.3 listen() 3.4 accept() 3.5 connect() 3.6 close() 3.7 recv()、send() 3.8 recv…

云原生构建 微服务、容器化与容器编排

第1章 何为云原生&#xff0c;云原生为何而生 SOA也就是面向服务的架构 软件架构的发展主要经历了集中式架构、分布式架构以及云原生架构这几代架构的发展。 微服务架构&#xff0c;其实是SOA的另外一种实现方式&#xff0c;属于SOA的子集。 在微服务架构下&#xff0c;系统…

和数软件:区块链技术的爆发与冲击

什么是区块链&#xff1f;它是如何发展而来的&#xff1f;应用在哪些领域&#xff1f;将会对我国的社会经济产生哪些重大影响&#xff1f; 什么是区块链 区块链作为一种底层技术&#xff0c;最早的实践是数字货币。根据最早的中本聪定义&#xff0c;区块链实质上是一种基于网…

代码理解 pseudo_labeled = outputs.max(1)[1]

import torchls torch.Tensor([[0.2,0.4],[0.3,0.2]]) print(ls.max(1))

【CSP试题回顾】202009-1-称检测点查询

CSP-202009-1-称检测点查询 解题代码 #include <iostream> #include <vector> #include <cmath> #include <algorithm> using namespace std;int n, X, Y, x, y; struct MyDistance {int index;int dis; }; vector<MyDistance>list; bool cmp(…

Django工具

一、分页器介绍 1.1、介绍 分页,就是当我们在页面中显示一些信息列表,内容过多,一个页面显示不完,需要分成多个页面进行显示时,使用的技术就是分页技术 在django项目中,一般是使用3种分页的技术: 自定义分页功能,所有的分页功能都是自己实现django的插件 django-pagin…