鸿蒙之Web组件(混合开发)

注意:需要配置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 = ""
}

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值