前言導(dǎo)讀
鴻蒙next web組件這個(gè)專(zhuān)題之前一直想講一下 苦于沒(méi)有時(shí)間,周末把代碼研究的差不多了,所以就趁著現(xiàn)在這個(gè)時(shí)間節(jié)點(diǎn)分享給大家。也希望能對(duì)各位讀者網(wǎng)友工作和學(xué)習(xí)有幫助,廢話不多說(shuō)我們正式開(kāi)始。
效果圖
-
默認(rèn)頁(yè)面 上面H5 下面ArkUI

-
在H5輸入框輸入需要傳遞的參數(shù) 點(diǎn)擊按鈕發(fā)送到ArkUI 展示

-
在ArkU輸入框輸入需要傳遞的參數(shù) 點(diǎn)擊按鈕發(fā)送到H5端 展示

-
最終效果 H5調(diào)用ArkUI ArkUI調(diào)用H5完成流程

具體實(shí)現(xiàn)
-
H5調(diào) ArkUI
H5端代碼簡(jiǎn)單實(shí)現(xiàn)
<!-- MainPage.html -->
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="./css/main.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>testApp</title>
</head>
<script>
window.ohosCallNative.callNative('getProportion', {}, (data) => {
document.getElementsByTagName("html")[0].style.fontSize = data + 'px';
})
</script>
<body>
<div class="container">
<div class="selectConcat">
<div class="flex-input">
<input type="tel" id="phone" placeholder="請(qǐng)輸入你要傳輸?shù)臄?shù)據(jù)" oninput="changeVal(event)" value=""/>
</div>
</div>
<div class="bottom-tip" onclick="towebview()">發(fā)送數(shù)據(jù)給鴻蒙原生端</div>
<div class="select_tips">
<div id="phone_tip">來(lái)自鴻蒙原生的數(shù)據(jù)</div>
<div id="concat_tip"></div>
</div>
</div>
<script src="./js/mainPage.js"></script>
</body>
</html>
調(diào)用ArkUI原生方法
function towebview() {
let input = event.target.value;
const tel = document.getElementById('phone').value;
window.ohosCallNative.callNative('changeTel', { tel: tel });
}
添加js和ArkUI交互
Web({
src: $rawfile('MainPage.html'),
controller: this.webController
})
.javaScriptAccess(true)
.javaScriptProxy(this.jsBridge.javaScriptProxy)
.height('50%')
.onPageBegin(() => {
this.jsBridge.initJsBridge();
})
調(diào)用原生ArkUI 方法
get javaScriptProxy(): JavaScriptItem {
let result: JavaScriptItem = {
object: {
call: this.call
},
name: 'JSBridgeHandle',
methodList: ['call'],
controller: this.controller
}
return result;
}
call = (func: string, params: string): void => {
const paramsObject: ParamsItem = JSON.parse(params);
let result: Promise<string> = new Promise((resolve) => resolve(''));
switch (func) {
case 'chooseContact':
result = this.chooseContact();
break;
case 'changeTel':
result = this.changeTel(paramsObject);
break;
case 'changeAmount':
result = this.changeAmount();
break;
case 'getProportion':
result = this.getProportion();
break;
default:
break;
}
result.then((data: string) => {
this.callback(paramsObject?.callID, data);
})
}
/**
* Change tel function.
*/
changeTel = (params: ParamsItem): Promise<string> => {
Logger.info('手機(jī)號(hào)', JSON.stringify(params));
const tel: string = params.data.tel ?? '';
Logger.error("tel -- > "+tel)
AppStorage.set<string>('tel', tel);
return new Promise((resolve) => {
resolve('success');
})
}
我們通過(guò)JavaScriptItem 中的call 接收到H5那邊調(diào)用 ArkUI 這邊方法 拿到傳過(guò)來(lái)的數(shù)據(jù)然后從存儲(chǔ)再 AppStorage然后我們?cè)赨I上面展示
-
ArkUI 端代碼實(shí)現(xiàn)
import { webview } from '@kit.ArkWeb';
import { display } from '@kit.ArkUI';
import { promptAction } from '@kit.ArkUI';
import JSBridge from '../common/utils/JsBridge';
import { CommonConstants } from '../common/constant/CommonConstant';
import Logger from '../common/utils/Logger';
@Extend(TextInput) function inputStyle(){
.placeholderColor($r('app.color.placeholder_color'))
.height(45)
.fontSize(18)
.backgroundColor($r('app.color.background'))
.width('80%')
.padding({left:0})
.margin({top:12})
}
//線條樣式
@Extend(Line) function lineStyle(){
.width('100%')
.height(1)
.backgroundColor($r('app.color.line_color'))
}
//黑色字體樣式
@Extend(Text) function blackTextStyle(size?:number ,height?:number){
.fontColor($r('app.color.black_text_color'))
.fontSize(18)
.fontWeight(FontWeight.Medium)
}
@Entry
@Component
struct SelectContact {
@StorageLink('isClick') isClick: boolean = false;
@StorageLink('tel') phoneNumber: string = '';
@StorageLink('proportion') proportion: number = 0;
@State towebstr:string='';
@State chargeTip: Resource = $r('app.string.recharge_button');
webController: webview.WebviewController = new webview.WebviewController();
private jsBridge: JSBridge = new JSBridge(this.webController,this.towebstr,"獲取到的數(shù)據(jù)");
aboutToAppear() {
display.getAllDisplays((err, displayClass: display.Display[]) => {
if (err.code) {
Logger.error('SelectContact Page', 'Failed to obtain all the display objects. Code: ' + JSON.stringify(err));
return;
}
this.proportion = displayClass[0].densityDPI / CommonConstants.COMMON_VALUE;
Logger.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(displayClass));
});
}
build() {
Column() {
Web({
src: $rawfile('MainPage.html'),
controller: this.webController
})
.javaScriptAccess(true)
.javaScriptProxy(this.jsBridge.javaScriptProxy)
.height('50%')
.onPageBegin(() => {
this.jsBridge.initJsBridge();
})
Row(){
Text('原生').blackTextStyle()
TextInput({placeholder:'請(qǐng)輸入要傳遞給H5的數(shù)據(jù)'})
.maxLength(12)
.type(InputType.Normal)
.inputStyle()
.onChange((value:string)=>{
this.towebstr=value;
}).margin({left:20})
}.justifyContent(FlexAlign.SpaceBetween)
.width('100%')
.margin({top:8})
Line().lineStyle().margin({left:80})
Button('發(fā)送數(shù)據(jù)給網(wǎng)頁(yè)')
.width(CommonConstants.FULL_SIZE)
.height($r('app.float.button_height'))
.margin({ bottom: $r('app.float.button_margin_bottom'),top:20 })
.onClick(() => {
Logger.error("towebstr " +this.towebstr)
this.jsBridge.chooseContact();
this.webController.runJavaScript(`window.fromNative("${this.towebstr}")`)
})
Row(){
Text('來(lái)自H5的數(shù)據(jù)').fontSize(15).fontColor(Color.Gray)
Text(this.phoneNumber).fontSize(20).fontColor(Color.Red)
}.justifyContent(FlexAlign.Center).margin({top:20})
}
.width(CommonConstants.FULL_SIZE)
.height(CommonConstants.FULL_SIZE)
.backgroundColor($r('app.color.page_color'))
.padding({
left: $r('app.float.margin_left_normal'),
right: $r('app.float.margin_right_normal')
})
}
}
-
ArkUI 調(diào)用H5
Button('發(fā)送數(shù)據(jù)給網(wǎng)頁(yè)')
.width(CommonConstants.FULL_SIZE)
.height($r('app.float.button_height'))
.margin({ bottom: $r('app.float.button_margin_bottom'),top:20 })
.onClick(() => {
Logger.error("towebstr " +this.towebstr)
this.jsBridge.chooseContact();
this.webController.runJavaScript(`window.fromNative("${this.towebstr}")`)
})
-
H5 端接收
window.fromNative = (text) => {
document.getElementById('concat_tip').innerHTML = text
}
最后總結(jié):
鴻蒙這邊web組件和安卓的webview 以及ios的 wkwebview 比較像官方也給出了接口原生 ArkUI和H5能互相交互。文章案例中也給出具體的用法,各位可以查閱。如果有什么疑問(wèn)也可以留言, 如果需要學(xué)習(xí)更多鴻蒙的知識(shí)可以瓜子你好我B站教程
課程地址
B站課程地址:www.bilibili.com/cheese/play…
項(xiàng)目?jī)?nèi)容:
-
1 常用布局組件的學(xué)習(xí)
-
2 網(wǎng)絡(luò)請(qǐng)求工具類(lèi)封裝
-
3 arkui 生命周期啟動(dòng)流程
-
4 日志工具類(lèi)的封裝
-
5 自定義組合組件的封裝
-
6 路由導(dǎo)航跳轉(zhuǎn)的使用
-
7 本地地?cái)?shù)據(jù)的緩存 以及緩存工具類(lèi)的封裝
-
8 歡迎頁(yè)面的實(shí)現(xiàn)
-
9 登錄案例和自動(dòng)登錄效果實(shí)現(xiàn)
-
10 請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)分頁(yè)上拉加載 下拉刷新的實(shí)現(xiàn)
-
11 list數(shù)據(jù)懶加載實(shí)現(xiàn)
-
12 webview組件的使用
團(tuán)隊(duì)介紹
團(tuán)隊(duì)介紹:作者: 堅(jiān)果派-徐慶 堅(jiān)果派由堅(jiān)果等人創(chuàng)建,團(tuán)隊(duì)由12位華為HDE以及若干熱愛(ài)鴻蒙的開(kāi)發(fā)者和其他領(lǐng)域的三十余位萬(wàn)粉博主運(yùn)營(yíng)。專(zhuān)注于分享 HarmonyOS/OpenHarmony,ArkUI-X,元服務(wù),倉(cāng)頡,團(tuán)隊(duì)成員聚集在北京,上海,南京,深圳,廣州,寧夏等地,目前已開(kāi)發(fā)鴻蒙 原生應(yīng)用,三方庫(kù)60+,歡迎進(jìn)行課程,項(xiàng)目等合作。