鴻蒙與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%')}
}