注意:需要配置ohos.permission.INTERNET网络访问权限
概念
Web组件用于在应用程序中显示Web页面内容,为开发者提供页面加载、页面交互、页面调试等能力
通过网络路径方式加载
build() {
Column() {
Button("原生组件")
.onClick(() => {
promptAction.showToast({ message: "原生提示" })
})
Web({
src: 'https://www.bilibili.com/',
controller: new webview.WebviewController()
})
.width('100%')
.layoutWeight(1)
}
.width('100%')
.height('100%')
.padding(20)
}
通过资源文件方式加载
创建html文件,放入rawfile文件夹中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.title {
font-size: 30px;
}
</style>
</head>
<body>
<div class="title">h5页面</div>
</body>
</html>
Web({
src: $rawfile("demo.html"),
controller: new webview.WebviewController()
})
.width('100%')
.layoutWeight(1)
鸿蒙应用端和网页端的两种通信方式
1、通过创建端口通信
// 1. 需要使用controller 创建两个端口
// 2. 需要把其中一个端口传给网页h5
// 3. 网页h5用端口给原生端发消息
// 4. 原生端用剩下的端口来接消息
2、通过调用接口方法
应用侧可以通过runJavaScript()方法调用前端页面的JavaScript相关函数。
class WebSDK {
controller: webview.WebviewController = new webview.WebviewController()
async openPhoto() {
const photo = new picker.PhotoViewPicker()
const result = await photo.select({
maxSelectNumber: 9,
MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE
})
this.controller.runJavaScript(`getPhotoUrl('${result.photoUris[0]}')`)
}
}
在Web组件初始化时调用javaScriptProxy()接口
import { webview } from '@kit.ArkWeb'
import { promptAction } from '@kit.ArkUI'
class WebSDK {
openPhoto() {
promptAction.showToast({ message: '打开相册' })
}
}
@Entry
@Component
struct ConnectPage {
controller: webview.WebviewController = new webview.WebviewController()
build() {
Column() {
Button("发送消息到h5")
.margin({
bottom: 100
})
Web({
src: $rawfile("demo2.html"),
controller: this.controller
})
.width('100%')
.layoutWeight(1)
.javaScriptProxy({
name: 'heima',
object: new WebSDK(),
methodList: ["openPhoto"],
controller: this.controller
})
}
.width('100%')
.height('100%')
}
}
class DataResult {
type: string = ""
message: string = ""
}