ArkTS开发系列之Web组件的学习(2.9)
上篇回顾:ArkTS开发系列之事件(2.8.2手势事件)
本篇内容: ArkTS开发系列之Web组件的学习(2.9)
一、知识储备
Web组件就是用来展示网页的一个组件。具有页面加载、页面交互以及页面调试功能
1. 加载网络页面
Web({ src: this.indexUrl, controller: this.webViewController })
2. 加载本地页面
Web({ src: $rawfile('local.html'), controller: this.webViewController })
3. 加载html格式的文本数据
- 该示例中,是点击button后开始加载html格式的文本数据
Button('加载html文本内容').onClick(event => {this.webViewController.loadData("<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>","text/html","UTF-8");})Web({ src: this.indexUrl, controller: this.webViewController })
4.深色模式设置
Web({ src: this.indexUrl, controller: this.webViewController }).darkMode(WebDarkMode.On) //设置深色模式.forceDarkAccess(true)//强制生效
5. 文件上传
Web({ src: $rawfile('local.html'), controller: this.webViewController }).onShowFileSelector(event=>{//设置要上传的文件路径let fileList: Array<string> =[]if (event) {event.result.handleFileList(fileList)}return true;})
6. 在新容器中打开页面
- 通过multiWindowAccess()来设置是否允许网页在新窗口中打开。有新窗口打开时,应用侧会在onWindowNew()接口中收到新窗口事件,需要我们在此接口中处理web组件的窗口请求
.onWindowNew(event=>{
}
- 如果开发者在onWindowNew()接口通知中不需要打开新窗口,需要将ControllerHandler.setWebController()接口返回值设置成null。
7. 管理位置权限
.geolocationAccess(true)
8. 应用调用html的js函数
Web({ src: $rawfile('local.html'), controller: this.webViewController }).javaScriptAccess(true)
this.webViewController.runJavaScript('htmlTest()')
9. 前端调用应用函数
- 在web组件初始化的时候注入javaScriptProxy()
@State testObj: TestClass = new TestClass(); //注册应用内js调用函数的对象Web({ src: $rawfile('local.html'), controller: this.webViewController }).javaScriptProxy({//将对角注入到web端object: this.testObj,name: 'testObjName',methodList: ['test'],controller: this.webViewController})
- 在web组件初始化完成后注入registerJavaScriptProxy()
this.webviewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test", "toString"]);
10. 应用与前端页面数据通道
aboutToAppear() {try {//1.在这里初始化portsthis.ports = this.webViewController.createWebMessagePorts();this.ports[1].onMessageEvent((result: webview.WebMessage) => { //2.接收消息,并根据业务处理消息let msg = '读取网页消息'if (typeof (result) == 'string') {msg = msg + result;} else if (typeof (result) == 'object') {if (result instanceof ArrayBuffer) {msg = msg + " result length: " + result.byteLength;} else {console.error('msg not support')}} else {console.error('msg not support')}this.receiveMsgFromHtml = msg;// 3、将另一个消息端口(如端口0)发送到HTML侧,由HTML侧保存并使用。this.webViewController.postMessage('__init_port__', [this.ports[0]], "*");})} catch (err) {console.error('err: ' + JSON.stringify(err))}}//4.给html发消息this.ports[1].postMessageEvent(this.sendFromEts)
11. 管理web组件的页面跳转和浏览记录
- 返回上一页
this.controller.backward()
- 进入下一页
this.controller.forward()
- 从web组件跳转到hap应用内的页面
Web({ controller: this.controller, src: $rawfile('route.html') }).onUrlLoadIntercept(event => {let url: string = event.data as string;if (url.indexOf('native://') === 0) {router.pushUrl({ url: url.substring(9) })return true;}return false;})
- 跨应用的页面跳转
call.makeCall(url.substring(6), err => {if (!err) {console.info('打电话成功')} else {console.info('拨号失败' + JSON.stringify(err))}})
12. 管理Cookie及数据存储
Cookie信息保存在应用沙箱路径下/proc/{pid}/root/data/storage/el2/base/cache/web/Cookiesd的文件中。
由WebCookieManager管理cookie
webview.WebCookieManager.setCookie('https://www.baidu.com','val=yes') //存储cookie
- 四种缓存策略(Cache)
Default : 优先使用未过期的缓存,如果缓存不存在,则从网络获取。
None : 加载资源使用cache,如果cache中无该资源则从网络中获取。
Online : 加载资源不使用cache,全部从网络中获取。
Only :只从cache中加载资源。 - 清除缓存
this.controller.removeCache(true);
- 是否持久化缓存domStorageAccess
domStorageAccess(true) ///true是Local Storage持久化存储;false是Session Storage,会随会话生命周期释放
13. 自定义页面请求响应
通过对onIntercerptRequest接口来实现自定义
.onInterceptRequest((event?: Record<string, WebResourceRequest>): WebResourceResponse => {if (!event) {return new WebResourceResponse();}let mRequest: WebResourceRequest = event.request as WebResourceRequest;console.info('url: ' + mRequest.getRequestUrl())if (mRequest.getRequestUrl().indexOf('https://www.baidu.com') === 0) {this.responseResource.setResponseData(this.webdata)this.responseResource.setResponseEncoding('utf-8')this.responseResource.setResponseMimeType('text/html')this.responseResource.setResponseCode(200);this.responseResource.setReasonMessage('OK')return this.responseResource;}return;})
14.
- 第一步
aboutToAppear() {// 配置web开启调试模式web_webview.WebviewController.setWebDebuggingAccess(true);}
- 第二步
// 添加映射
hdc fport tcp:9222 tcp:9222
// 查看映射
hdc fport ls
- 第三步
在电脑端chrome浏览器地址栏中输入chrome://inspect/#devices,页面识别到设备后,就可以开始页面调试。
二、 效果一览
三、 源码大杂烩
import webview from '@ohos.web.webview'
import router from '@ohos.router';
import call from '@ohos.telephony.call';@Entry
@Component
struct Index {controller: webview.WebviewController = new webview.WebviewController();responseResource: WebResourceResponse = new WebResourceResponse();@State webdata: string = "<!DOCTYPE html>\n" +"<html>\n" +"<head>\n" +"<title>将www.baidu.com改成我</title>\n" +"</head>\n" +"<body>\n" +"<h1>将www.baidu.com改成我</h1>\n" +"</body>\n" +"</html>"build() {Column() {Button('上一页').onClick(() => {this.controller.backward()})Button('下一页').onClick(() => {this.controller.forward()})Web({ controller: this.controller, src: 'www.baidu.com' })// Web({ controller: this.controller, src: $rawfile('route.html') }).onUrlLoadIntercept(event => {let url: string = event.data as string;if (url.indexOf('native://') === 0) {router.pushUrl({ url: url.substring(9) })return true;} else if (url.indexOf('tel://') === 0) {call.makeCall(url.substring(6), err => {if (!err) {console.info('打电话成功')} else {console.info('拨号失败' + JSON.stringify(err))}})return true;}return false;}).onInterceptRequest((event?: Record<string, WebResourceRequest>): WebResourceResponse => {if (!event) {return new WebResourceResponse();}let mRequest: WebResourceRequest = event.request as WebResourceRequest;console.info('url: ' + mRequest.getRequestUrl())if (mRequest.getRequestUrl().indexOf('https://www.baidu.com') === 0) {this.responseResource.setResponseData(this.webdata)this.responseResource.setResponseEncoding('utf-8')this.responseResource.setResponseMimeType('text/html')this.responseResource.setResponseCode(200);this.responseResource.setReasonMessage('OK')return this.responseResource;}return;})// webview.WebCookieManager.setCookie('https://www.baidu.com','val=yes')}.width('100%').height('100%')}
}
import webview from '@ohos.web.webview';
import common from '@ohos.app.ability.common';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import geoLocationManager from '@ohos.geoLocationManager';let context = getContext(this) as common.UIAbilityContext;
let atManager = abilityAccessCtrl.createAtManager();
try {atManager.requestPermissionsFromUser(context, ["ohos.permission.LOCATION", "ohos.permission.APPROXIMATELY_LOCATION"], (err, data) => {// let requestInfo: geoLocationManager.LocationRequest = {// 'priority': 0x203,// 'scenario': 0x300,// 'maxAccuracy': 0// };//// let locationChange = (location: geoLocationManager.Location): void => {// if (location) {// console.error('location = ' + JSON.stringify(location))// }// };//// try {// geoLocationManager.on('locationChange', requestInfo, locationChange);// geoLocationManager.off('locationChange', locationChange);// } catch (err) {// console.error('err : ' + JSON.stringify(err))// }console.info('data: ' + JSON.stringify(data))console.info("data permissions: " + JSON.stringify(data.permissions))console.info("data authResults: " + JSON.stringify(data.authResults))})
} catch (err) {console.error('err : ', err)
}class TestClass {constructor() {}test() {return '我是应用内函数';}
}@Entry
@Component
struct Index {@State indexUrl: string = 'www.baidu.com';webViewController: webview.WebviewController = new webview.WebviewController();dialog: CustomDialogController | null = null@State testObj: TestClass = new TestClass(); //注册应用内js调用函数的对象ports: webview.WebMessagePort[]; //消息端口@State sendFromEts: string = '这消息将被发送到html'@State receiveMsgFromHtml: string = '这将展示接收到html发来的消息'aboutToAppear() {try {//1.在这里初始化portsthis.ports = this.webViewController.createWebMessagePorts();this.ports[1].onMessageEvent((result: webview.WebMessage) => { //2.接收消息,并根据业务处理消息let msg = '读取网页消息'if (typeof (result) == 'string') {msg = msg + result;} else if (typeof (result) == 'object') {if (result instanceof ArrayBuffer) {msg = msg + " result length: " + result.byteLength;} else {console.error('msg not support')}} else {console.error('msg not support')}this.receiveMsgFromHtml = msg;// 3、将另一个消息端口(如端口0)发送到HTML侧,由HTML侧保存并使用。this.webViewController.postMessage('__init_port__', [this.ports[0]], "*");})} catch (err) {console.error('err: ' + JSON.stringify(err))}}build() {Column() {Button('加载html文本内容').onClick(event => {this.webViewController.loadData("<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>","text/html","UTF-8");})Button('调用html的js函数').onClick(event => {this.webViewController.runJavaScript('htmlTest()')})Button('web组件初始化完成后注入').onClick(event => {this.webViewController.registerJavaScriptProxy(this.testObj, "testObjName", ["test"]);})Text(this.receiveMsgFromHtml).fontSize(33)Button('给html端发消息').onClick(() => {try {if (this.ports && this.ports[1]) {//4.给html发消息this.ports[1].postMessageEvent(this.sendFromEts)} else {console.error('ports init fail')}} catch (err) {console.error('ports init fail ' + JSON.stringify(err))}})// Web({ src: this.indexUrl, controller: this.webViewController })// .darkMode(WebDarkMode.On) //设置深色模式// .forceDarkAccess(true) //强制生效// Web({ src: $rawfile('window.html'), controller: this.webViewController })// .javaScriptAccess(true)// .multiWindowAccess(true)// .onWindowNew(event=>{// if (this.dialog) {// this.dialog.close()// }//// let popController: webview.WebviewController = new webview.WebviewController();//// this.dialog = new CustomDialogController({// builder: NewWebViewComp({webviewController1: popController})// })// this.dialog.open()// //将新窗口对应WebviewController返回给Web内核。// //如果不需要打开新窗口请调用event.handler.setWebController接口设置成null。// //若不调用event.handler.setWebController接口,会造成render进程阻塞。// event.handler.setWebController(popController)// })Web({ src: $rawfile('postMsg.html'), controller: this.webViewController })// Web({ src: $rawfile('local.html'), controller: this.webViewController })// .onShowFileSelector(event => {// //设置要上传的文件路径// let fileList: Array<string> = []// if (event) {// event.result.handleFileList(fileList)// }// return true;// })// .geolocationAccess(true)// .javaScriptAccess(true)// .javaScriptProxy({//将对角注入到web端// object: this.testObj,// name: 'testObjName',// methodList: ['test'],// controller: this.webViewController// })// .onGeolocationShow(event => {// AlertDialog.show({// title: '位置权限请求',// message: '是否允许获取位置信息',// primaryButton: {// value: '同意',// action: () => {// event.geolocation.invoke(event.origin, true, false);// }// },// secondaryButton: {// value: '取消',// action: () => {// if (event) {// event.geolocation.invoke(event.origin, false, false)// }// }// },// cancel: () => {// if (event) {// event.geolocation.invoke(event.origin, false, false)// }// }//// })// })}.width('100%').height('100%')}
}
相关文章:

ArkTS开发系列之Web组件的学习(2.9)
上篇回顾:ArkTS开发系列之事件(2.8.2手势事件) 本篇内容: ArkTS开发系列之Web组件的学习(2.9) 一、知识储备 Web组件就是用来展示网页的一个组件。具有页面加载、页面交互以及页面调试功能 1. 加载网络…...
postman接口工具的详细使用教程
Postman 是一种功能强大的 API 测试工具,可以帮助开发人员和测试人员轻松地发送 HTTP 请求并分析响应。以下是对 Postman 接口测试工具的详细介绍: 安装与设置 安装步骤 访问 Postman 官网,点击右上角的“Download”按钮。 选择你的操作系统…...
C语言经典例题-17
1.最小公倍数 正整数A和正整数B的最小公倍数是指能被A和B整除的最小的正整数,设计一个算法,求输入A和B的最小公倍数。 输入描述:输入两个正整数A和B。 输出描述:输出A和B的最小公倍数。 输入:5 7 输出:…...
鸿蒙学习(-)
.ets文件结构 //页面入口 Entry //组件 Component struct test{//页面结构build(){//容器 **一个页面只能有一个根容器,父容器要有大小设置**}1、Column 组件 沿垂直方向布局的组件,可以包含子组件 接口 Column({space}) space的参数为string | numbe…...

【TB作品】MSP430G2553,单片机,口袋板, 烘箱温度控制器
题3 烘箱温度控制器 设计一个基于MSP430的温度控制器,满足如下技术指标: (1)1KW 电炉加热,最度温度为110℃ (2)恒温箱温度可设定,温度控制误差≦2℃ (3)实时显…...

PCM、WAV,立体声,单声道,正弦波等音频素材
1)PCM、WAV音频素材,分享给将要学习或者正在学习audio开发的同学。 2)内容属于原创,若转载,请说明出处。 3)提供相关问题有偿答疑和支持。 常用的Audio PCM WAV不同采样率,不同采样深度&#…...
基于深度学习的图像去雾
基于深度学习的图像去雾 图像去雾是指从有雾的图像中恢复清晰图像的过程。传统的图像去雾方法(如暗原色先验、图像分层法等)在某些情况下表现良好,但在复杂场景下效果有限。深度学习方法利用大量的数据和强大的模型能力,在图像去…...
中国电子学会青少年编程等级考试真题下载
全国青少年软件编程等级考试真题下载,有答案解析 1. 图形化Scratch一级下载 链接:https://pan.baidu.com/s/1C9DR9-hT1RUY3417Yc8RZQ?pwdg8ac 提取码:g8ac 2.图形化Scratch二级下载 链接:https://pan.baidu.com/s/1HI7GaI4ii…...

PostMan动态设置全局变量
1. 前言 在开发过程中调试接口,一般都会使用PostMan。 其中有几个变量可能是好几个接口共用的,就会出现频繁手动复制(ctrlc)、粘贴(ctrlv)的情况。 这个过程得非常留意,生怕复制错了,或删减了某些东西,导致接口报错。…...

ACL 2023事件相关(事件抽取、事件关系抽取、事件预测等)论文汇总
ACL 2023事件抽取相关(事件抽取、事件关系抽取、事件预测等)论文汇总,后续会更新全部的论文讲解。 Event Extraction Code4Struct: Code Generation for Few-Shot Event Structure Prediction 数据集:ACE 2005 动机:与自然语言相比…...

力扣:59. 螺旋矩阵 II(Java,模拟)
目录 题目描述示例 1:代码实现 题目描述 给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。 示例 1: 输入:n 3 输出:[[1,2,3],[8,9,4],[7,6,5…...

记录SpringBoot启动报错解决
记录SpringBoot启动报错解决 报错现场 Failed to configure a DataSource: url attribute is not specified and no embedded datasource could be configured. Reason: Failed to determine a suitable driver class Action: Consider the following:If you want an embedde…...
微软代码页标识符 (Code Page Identifiers)
代码页标识符 (Code Page Identifiers) 双语对照 Identifiere标识符.NET Name.NET 名称Additional information其他信息037IBM037IBM EBCDIC US-CanadaIBM EBCDIC US-Canada437IBM437OEM United StatesOEM 美国500IBM500IBM EBCDIC InternationalIBM EBCDIC 国际字符集708ASMO…...
刷题——二叉树的后续遍历
方法一:双指针法 void postorder(TreeNode* root, vector<int>&res){if(root NULL) return;postorder(root->left,res);postorder(root->right,res);res.push_back(root->val);}vector<int> postorderTraversal(TreeNode* root) {// wri…...

用友U8 Cloud smartweb2.showRPCLoadingTip.d XXE漏洞复现
0x01 产品简介 用友U8 Cloud 提供企业级云ERP整体解决方案,全面支持多组织业务协同,实现企业互联网资源连接。 U8 Cloud 亦是亚太地区成长型企业最广泛采用的云解决方案。 0x02 漏洞概述 用友U8 Cloud smartweb2.showRPCLoadingTip.d 接口处存在XML实体,攻击者可通过该漏…...
React中的事件绑定的四种方式
1.在构造函数中绑定事件 constructor(props) {super(props);this.handleClick this.handleClick.bind(this);}2.在调用时显式绑定 <button onClick{this.handleClick.bind(this)}>Click me</button>3.使用箭头函数 handleClick () > {console.log(Button cli…...
小文件过多的解决方法(不同阶段下的治理手段,SQL端、存储端以及计算端)
上一篇介绍了小文件出现的原因以及为什么治理小文件问题迫在眉睫,本篇将为读者讲述在不同阶段下小文件治理的最佳手段以及如何针对性的解决小文件过多的问题。 小文件过多如何解决、治理方法 小文件是特别常见的现象,解决小文件问题迫在眉睫࿰…...

SGPT论文阅读笔记
这是篇想要用GPT来提取sentence embedding的工作,提出了两个框架,一个是SGPT-BE,一个是SGPT-CE,分别代表了Bi-Encoder setting和Cross-Encoder setting。CE的意思是在做阅读理解任务时,document和query是一起送进去&am…...
虚拟机与主机的网络桥接
虚拟机网路桥接是一种网络配置方式,它允许虚拟机与物理网络中的其他设备直接通信。在桥接模式下,虚拟机的网络接口通过主机的物理网卡连接到局域网中,就像主机本身一样,拥有自己的MAC地址和IP地址。这种方式使得虚拟机可以像独立的…...

urfread刷算法题day1|LeetCode2748.美丽下标的数目
题目 题目链接 LeetCode2748.美丽下标对的数目 题目描述 给你一个下标从 0 开始的整数数组 nums 。 如果下标对 i、j 满足 0 ≤ i < j < nums.length , 如果 nums[i] 的 第一个数字 和 nums[j] 的 最后一个数字 互质 , 则认为 nums[i] 和 nums…...

渗透实战PortSwigger靶场-XSS Lab 14:大多数标签和属性被阻止
<script>标签被拦截 我们需要把全部可用的 tag 和 event 进行暴力破解 XSS cheat sheet: https://portswigger.net/web-security/cross-site-scripting/cheat-sheet 通过爆破发现body可以用 再把全部 events 放进去爆破 这些 event 全部可用 <body onres…...
laravel8+vue3.0+element-plus搭建方法
创建 laravel8 项目 composer create-project --prefer-dist laravel/laravel laravel8 8.* 安装 laravel/ui composer require laravel/ui 修改 package.json 文件 "devDependencies": {"vue/compiler-sfc": "^3.0.7","axios": …...
Xen Server服务器释放磁盘空间
disk.sh #!/bin/bashcd /run/sr-mount/e54f0646-ae11-0457-b64f-eba4673b824c # 全部虚拟机物理磁盘文件存储 a$(ls -l | awk {print $NF} | cut -d. -f1) # 使用中的虚拟机物理磁盘文件 b$(xe vm-disk-list --multiple | grep uuid | awk {print $NF})printf "%s\n"…...

深度学习水论文:mamba+图像增强
🧀当前视觉领域对高效长序列建模需求激增,对Mamba图像增强这方向的研究自然也逐渐火热。原因在于其高效长程建模,以及动态计算优势,在图像质量提升和细节恢复方面有难以替代的作用。 🧀因此短时间内,就有不…...
纯 Java 项目(非 SpringBoot)集成 Mybatis-Plus 和 Mybatis-Plus-Join
纯 Java 项目(非 SpringBoot)集成 Mybatis-Plus 和 Mybatis-Plus-Join 1、依赖1.1、依赖版本1.2、pom.xml 2、代码2.1、SqlSession 构造器2.2、MybatisPlus代码生成器2.3、获取 config.yml 配置2.3.1、config.yml2.3.2、项目配置类 2.4、ftl 模板2.4.1、…...

在Mathematica中实现Newton-Raphson迭代的收敛时间算法(一般三次多项式)
考察一般的三次多项式,以r为参数: p[z_, r_] : z^3 (r - 1) z - r; roots[r_] : z /. Solve[p[z, r] 0, z]; 此多项式的根为: 尽管看起来这个多项式是特殊的,其实一般的三次多项式都是可以通过线性变换化为这个形式…...
多模态图像修复系统:基于深度学习的图片修复实现
多模态图像修复系统:基于深度学习的图片修复实现 1. 系统概述 本系统使用多模态大模型(Stable Diffusion Inpainting)实现图像修复功能,结合文本描述和图片输入,对指定区域进行内容修复。系统包含完整的数据处理、模型训练、推理部署流程。 import torch import numpy …...
Vue 模板语句的数据来源
🧩 Vue 模板语句的数据来源:全方位解析 Vue 模板(<template> 部分)中的表达式、指令绑定(如 v-bind, v-on)和插值({{ }})都在一个特定的作用域内求值。这个作用域由当前 组件…...
云原生周刊:k0s 成为 CNCF 沙箱项目
开源项目推荐 HAMi HAMi(原名 k8s‑vGPU‑scheduler)是一款 CNCF Sandbox 级别的开源 K8s 中间件,通过虚拟化 GPU/NPU 等异构设备并支持内存、计算核心时间片隔离及共享调度,为容器提供统一接口,实现细粒度资源配额…...

数据结构第5章:树和二叉树完全指南(自整理详细图文笔记)
名人说:莫道桑榆晚,为霞尚满天。——刘禹锡(刘梦得,诗豪) 原创笔记:Code_流苏(CSDN)(一个喜欢古诗词和编程的Coder😊) 上一篇:《数据结构第4章 数组和广义表》…...