Uniapp 實現 與 外部 HTML 頁面通信
在 uniapp 中 經常會 內嵌 html, 並且 有時候會還有 相互通信 的需求 :
這裏 總結了 兩種形式
APP 中 nvue 使用 web-view 實現html 通信;
H5 中 vue 使用 iframe 實現html 通信;
這裏結合了兩種;
從 HTML 調用 uniapp 接口
<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
<script type="text/javascript">
//js SDK 加載成功
document.addEventListener('UniAppJSBridgeReady', function() {
// 監聽按鈕事件
document.getElementById('to_shiming').addEventListener('click', function() {
let data_shiming = {
action: '1'
}
// .nvue 可以接收的事件
uni.postMessage({
data: data_shiming
});
// .vue 可以接收的事件
window.parent.postMessage(data_shiming, '*')
});
})
//接收來自 .vue 的數據 和 參數 間接 調用 函數
window.addEventListener('message', function(event) {
// event.origin --發送者的源
// event.source --發送者的window對象
// event.data --數據
if (event.data) {
//此處執行事件
if (event.data.action == 66) {
console.log("event.data.time:", event.data.time)
setBirDayInit(event.data.time)
setBirDay(true)
}
}
})
// .nvue 直接調用函數
function setBirDay(data) {
}
// .nvue 直接調用函數
function setBirDayInit(day) {
}
</script>
從 uniapp 調用 html 網頁;這個是爲什麼兩種方式的原因
這裏要分爲兩種情況;
一種是從 .nvue 調用 html
<template>
<view class="web-view">
<web-view class="web-view" :src="url" ref="webview" @onPostMessage="handlePostMessage" @receivedtitle="onReceivedTitle">
</web-view>
</view>
</template>
<script>
export default {
methods: {
handlePostMessage: function(data) {
// 獲取網頁的參數
console.log("得到參數", data.detail);
},
onPageFinish: function(e) {
this.$refs.webview.evalJs("方法名('" + 參數 + "')");
this.$refs.webview.evalJs("方法名('參數')");
},
}
}
</script>
<style scoped>
.web-view {
flex: 1;
flex-direction: column;
background-color: #f5f5f5;
}
.sendMessage {
width: 750rpx;
position: fixed;
bottom: 0rpx;
}
</style>
一種是從 .vue 調用 html
<template>
<view class="bir-webviwe">
<iframe id="iframe" class="viewiframe" :src="url" ref="iframe" @onload="onLoad"></iframe>
</view>
</template>
<script>
export default {
mounted() {
// 接受子頁面發來的信息
window.addEventListener("message", this.ReceiveMessage);
//console.log("------>",this.url)
},
methods: {
onLoad() {
console.log("---------------->onLoad")
},
ReceiveMessage(event) {
if (event.data && event.data.data && event.data.data.arg) {
console.log("iframe 參數 event.data:", event.data.data.arg)
}
},
SendMessage() {
let str = toolTimer.formatTime(new Date(), "yyyy-MM-dd")
let data = {
action: 66,
time: str
}
document.getElementById('iframe').contentWindow.postMessage(data, '*')
}
}
}
</script>
<style lang="scss" scoped>
.bir-webviwe {
position: absolute;
bottom: 0;
left: 0;
right: 0;
top: 0;
.viewiframe {
width: 100%;
height: 100%;
background: #FFFFFF
}
}
</style>