一、內(nèi)嵌網(wǎng)頁向uni-app
通信
1疯趟、內(nèi)嵌網(wǎng)頁向uni-app
發(fā)消息
在we-view
訪問的網(wǎng)頁內(nèi)引入uni.webview.1.5.4.js
,通過uni.postMessage(OBJECT)
向應用發(fā)送消息谋梭,在wb-view
的message
事件回調(diào)event.detail.data
中接受消息信峻。
注意:
1、傳遞的消息瓮床,必須寫在data對象中盹舞。
2、event.detail.data
中的數(shù)據(jù)隘庄,以數(shù)組的形式接收每次post
的消息(注:支付寶小程序除外踢步,支付寶小程序中以對象形式接收)。
以下為內(nèi)嵌網(wǎng)頁代碼
// index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script type="text/javascript" src="https://gitee.com/dcloud/uni-app/raw/dev/dist/uni.webview.1.5.4.js">
</script>
</head>
<body>
<script>
// 待觸發(fā) `UniAppJSBridgeReady` 事件后峭沦,即可調(diào)用 uni 的 API贾虽。
document.addEventListener('UniAppJSBridgeReady', function() {
// 向應用發(fā)送消息
uni.postMessage({
data: {
action: 'message'
}
});
});
</script>
</body>
</html>
2、uni-app
接收消息
在組建web-view
中監(jiān)聽message
方法吼鱼,如下:
<template>
<web-view @message="message" src="xxxxxxxxx"></web-view>
</template>
<script>
export default {
data() {
return {};
},
methods: {
message(arg) {
console.log(arg);
},
}
};
</script>
通過判斷上述arg
傳遞過來的值蓬豁,我們可以跳轉或者事件的觸發(fā)。
二菇肃、uni-app
應用向內(nèi)嵌網(wǎng)頁通信
1地粪、應用給內(nèi)嵌網(wǎng)頁發(fā)消息
//此對象相當于html5plus里的plus.webview.currentWebview()。在uni-app里vue頁面直接使用plus.webview.currentWebview()無效
const currentWebview = this.$scope.$getAppWebview().children()[0];
currentWebview.evalJS(`msgFromUniapp({
userInfo:{
name:'張三'
}
})`);
const
_funName = 'msgFromUniapp',
_data = uni.getStorageSync('userInfo');
const currentWebview = this.$scope.$getAppWebview().children()[0];
currentWebview.evalJS(`${_funName}(${JSON.stringify(_data)})`);
2琐谤、內(nèi)嵌網(wǎng)頁接受消息
window.msgFromUniapp= function(arg) {
console.log(arg);
console.log(JSON.stringify(arg));
}
三蟆技、真實案例
內(nèi)嵌網(wǎng)頁想獲取應用的頭像、昵稱斗忌、ID质礼。
1、內(nèi)嵌網(wǎng)頁代碼
// index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script type="text/javascript" src="https://gitee.com/dcloud/uni-app/raw/dev/dist/uni.webview.1.5.4.js">
</script>
</head>
<body>
<script>
// 待觸發(fā) `UniAppJSBridgeReady` 事件后织阳,即可調(diào)用 uni 的 API眶蕉。
document.addEventListener('UniAppJSBridgeReady', function() {
// 向應用發(fā)送消息
uni.postMessage({
data: {
action: 'getUserInfo'
}
});
});
window.msgFromUniapp= function(arg) {
console.log(arg);
console.log(JSON.stringify(arg));
}
</script>
</body>
</html>
2、uni-app
代碼
<template>
<web-view @message="message" src="xxxxxxxxx"></web-view>
</template>
<script>
export default {
data() {
return {};
},
methods: {
message(arg) {
if (arg.detail.data[0].action === 'getUserInfo') {
this.getUserInfo();
}
},
getUserInfo() {
const currentWebview = this.$scope.$getAppWebview().children()[0];
currentWebview.evalJS(`msgFromUniapp({
userInfo:{
name:'張三'
}
})`);
}
}
};
</script>