当前位置: 首页 > news >正文

鸿蒙Next Web组件详解:属性设置与事件处理实战

在鸿蒙应用开发中,Web组件是展示网页内容的核心控件,它提供了强大的网页渲染能力和交互支持。今天我们将深入探讨如何在鸿蒙Next中为Web组件设置基本属性和事件。

1. Web组件简介

Web组件是鸿蒙系统中提供网页显示能力的核心组件,从API version 6开始支持。它允许开发者在应用中嵌入Web内容,既可以加载在线网页,也可以显示本地HTML文件。

一个页面仅支持一个Web组件,该组件会全屏显示。如果页面中还有其他组件,会被Web组件覆盖,且Web组件不跟随转场动画。

2. 基本属性设置

2.1 src属性

src 属性是Web组件最基础的属性,用于设置需要显示的网页地址:

javascript

Web({ src: 'https://www.example.com', controller: this.controller })

需要注意的是,在线网址的域名必须使用HTTPS协议且经过ICP备案

2.2 加载本地网页

除了加载在线网页,Web组件还可以显示本地HTML文件:

javascript

// 将HTML文件放在main/resources/rawfile目录下
Web({ src: $rawfile('index.html'), controller: this.controller })

2.3 常用属性配置

Web组件提供了多个属性来定制其行为:

javascript

Web({ src: 'https://www.example.com', controller: this.controller }).fileAccess(true) // 设置是否开启通过$rawfile访问应用中rawfile路径的文件.javaScriptAccess(true) // 设置是否允许执行JavaScript脚本.imageAccess(true) // 设置是否允许自动加载图片资源.zoomAccess(true) // 设置是否支持手势进行缩放.textZoomRatio(100) // 设置页面的文本缩放百分比,默认100%

3. 事件处理

Web组件提供了丰富的事件回调,让开发者能够监控网页加载状态和处理交互。

3.1 网页加载事件

javascript

Web({ src: 'https://www.example.com', controller: this.controller }).onPageStart(e => {console.info('网页开始加载: ' + e.url);}).onPageFinish(e => {console.info('网页加载完成: ' + e.url);}).onError(e => {console.info('加载出错 - URL: ' + e.url);console.info('错误代码: ' + e.errorCode);console.info('错误描述: ' + e.description);})

3.2 进度监控事件

javascript

@State progress: number = 0;
@State hideProgress: boolean = true;Web({ src: 'https://www.example.com', controller: this.controller }).onProgressChange(e => {this.progress = e.newProgress;// 当进度100%时,进度条消失if (this.progress === 100) {this.hideProgress = true;} else {this.hideProgress = false;}})

3.3 JavaScript对话框事件

javascript

Web({ src: 'https://www.example.com', controller: this.controller }).onConfirm((event) => {// 获取回调函数的参数let url = event.url;let message = event.message;let result = event.result;// 显示自定义弹框AlertDialog.show({ title: '', message: '--' + message });return true;})

4. 控制器方法

WebController提供了多种控制网页行为的方法:

javascript

// 创建控制器
controller: WebController = new WebController();// 在Web组件中使用
Web({ src: 'https://www.example.com', controller: this.controller })// 使用方法
this.controller.forward(); // 前进
this.controller.backward(); // 后退
this.controller.refresh(); // 刷新
this.controller.stop(); // 停止加载
this.controller.clearHistory(); // 清除历史记录
this.controller.runJavaScript('test()'); // 执行JavaScript代码

5. 完整示例

下面是一个完整的Web组件使用示例:

javascript

// xxx.ets
@Entry
@Component
struct WebComponent {@State progress: number = 0;@State hideProgress: boolean = true;fileAccess: boolean = true;controller: WebController = new WebController();build() {Column() {// 进度条Progress({value: this.progress, total: 100}).color('#0000ff').visibility(this.hideProgress ? Visibility.None : Visibility.Visible)// 控制按钮Row({ space: 10 }) {Button('前进').onClick(() => { this.controller.forward() })Button('后退').onClick(() => { this.controller.backward() })Button('刷新').onClick(() => { this.controller.refresh() })Button('执行JS').onClick(() => {this.controller.runJavaScript({ script: 'test()',callback: (result: string) => { console.info(result); }})})}.width('100%').height(50)// Web组件Web({ src: 'https://www.example.com', controller: this.controller }).fileAccess(this.fileAccess).javaScriptAccess(true).height('100%').width('100%').onProgressChange(e => {this.progress = e.newProgress;if (this.progress === 100) {this.hideProgress = true;} else {this.hideProgress = false;}}).onPageEnd(e => {this.controller.runJavaScript('test()');console.info('url: ', e.url);})}}
}

6. 权限配置

使用Web组件加载在线网页时,需要在config.json文件中添加网络权限:

json

{"module": {"reqPermissions": [{"name": "ohos.permission.INTERNET"}]}
}

7. 与JavaScript交互

Web组件支持与页面中的JavaScript代码进行交互,这是通过registerJavaScriptProxyrunJavaScript方法实现的。

7.1 注册JavaScript代理

javascript

// 定义要注入的对象
testObj = {test: (data) => {this.dataFromHtml = data;return 'ArkUI Web Component';},toString: () => {console.log('Web Component toString');}
}// 注册代理
this.controller.registerJavaScriptProxy({object: this.testObj,name: 'objName',methodList: ['test', 'toString'],
});
this.controller.refresh(); // 刷新使代理生效

7.2 HTML中调用注册的方法

html

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<body>
<button οnclick="htmlTest()">调用Web组件里面的方法</button>
</body>
<script type="text/javascript">function htmlTest() {str = objName.test("来自HTML的参数");}
</script>
</html>

结语

Web组件是鸿蒙应用开发中非常强大的工具,它桥接了原生应用与Web内容。通过合理设置属性和事件处理,开发者可以创建出既具有原生性能又拥有Web灵活性的混合应用。掌握Web组件的使用,将为你的鸿蒙应用开发打开新世界的大门。

希望本篇博客能帮助你更好地理解和使用鸿蒙Next中的Web组件。如有任何问题,欢迎在评论区留言讨论!


文章转载自:

http://Y18j7v2W.bpmtL.cn
http://f4OYlyQN.bpmtL.cn
http://m9zG2k7J.bpmtL.cn
http://CooeXlvj.bpmtL.cn
http://5fC3K7v5.bpmtL.cn
http://50PRNsbB.bpmtL.cn
http://nij0dePE.bpmtL.cn
http://33rnUJkM.bpmtL.cn
http://ZU44MBFa.bpmtL.cn
http://JpNMlB3e.bpmtL.cn
http://442rSMn1.bpmtL.cn
http://BouwalBY.bpmtL.cn
http://iKkPQRr6.bpmtL.cn
http://U2bLl0xS.bpmtL.cn
http://pyljfwnu.bpmtL.cn
http://qEfWLZnr.bpmtL.cn
http://tNpJIKVh.bpmtL.cn
http://DkLLSQAP.bpmtL.cn
http://HfU9AQig.bpmtL.cn
http://LItZoe6c.bpmtL.cn
http://6HokYFMw.bpmtL.cn
http://SjCRHUcn.bpmtL.cn
http://0siDMAOG.bpmtL.cn
http://Vq5YE0Ql.bpmtL.cn
http://G1db6AGS.bpmtL.cn
http://jFPkYKhA.bpmtL.cn
http://bn3LI1vV.bpmtL.cn
http://aF6NV4U5.bpmtL.cn
http://J8tUiZxs.bpmtL.cn
http://TLu2ujAg.bpmtL.cn
http://www.dtcms.com/a/379556.html

相关文章:

  • Chaosblade常用命令和范例
  • Linux内存管理章节九: 打通虚拟与实体的桥梁:深入Linux内存映射机制
  • leetcode13:罗马数字转整数(哈希表模拟)
  • TCP协议的相关特性
  • 猎豹移动2025年Q2财报:营收2.952亿,接近盈亏平衡
  • Spring框架1—Spring的IOC核心技术1
  • LeetCode 2327.知道秘密的人数:动态规划/差分数组O(n)
  • 8年老测试分析,自动化测试的挑战与实施,一篇打通...
  • VBA即用型代码手册:另存为html文件SaveAs .Html File
  • 数字孪生:数据驱动下的虚实融合与技术落地方法论
  • 【前端Vue】el-dialog关闭后黑色遮罩依然存在如何解决?
  • 计算机视觉与模式识别前沿一览:2025年8月arXiv 热点研究趋势解析
  • 【Java】P1 Java由此开始:简介、下载安装与HelloJava
  • Katalog:AI语音文章播报工具,打造沉浸式听读体验
  • 细胞图像分割实战:用U-Net模型自动识别显微镜图像中的细胞
  • 如何理解MOS管规格书中标注的VDS?
  • JavaScript逆向SM国密算法
  • 炫彩VS动作指令:活体检测技术大比拼
  • 只读查询的“零分配”之路:EF Core + Dapper + MemoryPack 的组合优化
  • EMC电磁兼容进阶3讲培训:专题三 近场探头和频谱仪在EMC整改中的应用
  • 清理C盘回忆录
  • 对于单链表相关经典算法题:21. 合并两个有序链表及面试题 02.04. 分割链表的解析
  • 【代码随想录day 24】 力扣 78.集合
  • leetcode算法刷题的第三十二天
  • (done) CUDA 和 CPU 性能对比,矩阵加法和矩阵乘法对比
  • 事实上事实上
  • 【左程云算法07】队列和栈-链表数组实现
  • 关于亚马逊账号关联的思考——关于侵权
  • 【硬件-笔试面试题-84】硬件/电子工程师,笔试面试题(知识点:MOS管是损耗有哪些)
  • mybatis vs mybatis-plus