鸿蒙与web混合开发双向通信用runJavaScript和registerJavaScriptProxy
web
entry/src/main/resources/rawfile/1.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>混合开发</title>
</head>
<body><div></div><img src="./a.png" alt=""><button onclick="selectImg()">打开相册</button>
</body>
</html>
<script>//直接写js代码function changeImg(){//1.获取img这个元素const img = document.querySelector('img')//2.修改元素的属性img.src = './b.png'}async function selectImg(){//通知鸿蒙,让鸿蒙设备打开相册const res = await harmonyDevice.selectImage()const div = document.querySelector('div')div.innerText = JSON.stringify(res)}</script>
鸿蒙
import { webview } from '@kit.ArkWeb'
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import { promptAction } from '@kit.ArkUI'@Entry
@Component
struct Page {webController:WebviewController = new webview.WebviewController()selectImg(){const picker = new photoAccessHelper.PhotoViewPicker()return picker.select()}build() {Column(){// 1.想让网页干嘛,直接调网页的JS方法Button('鸿蒙-改变网页图片').onClick(()=>{// 控制器this.webController.runJavaScript('changeImg()')})// 2.网页控制鸿蒙测Button('注入鸿蒙的事件').onClick(()=>{promptAction.showToast({message:'注入成功'})// 1.先给网页一个对象,这个对象上包含了所有网页要用到的方法集合// 2.给这个对象起一个名字,让网页可以使用这个对象// 3.确定网页可以使用的方法集合this.webController.registerJavaScriptProxy({selectImage:async()=>{const res = await this.selectImg()return res}},"harmonyDevice",["selectImage"])})// 1.加载的地址// 2.控制Button('刷新页面').onClick(()=>{this.webController.refresh()})Web({// 本地:src:$rawfile('1.html'),// src:'https://www.amap.com/',controller:this.webController})}.width('100%').height('100%')}
}