在鸿蒙应用开发中,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代码进行交互,这是通过registerJavaScriptProxy
和runJavaScript
方法实现的。
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组件。如有任何问题,欢迎在评论区留言讨论!