突然有个需求,要uni中webview与H5直接进行通讯,本来想的找个例子copy下算了。没想到,很多都不能用啊。至于所谓的什么 @message和 @onPostMessage好像都不行。试验都没任何反应!
算了,自己写吧。我这主要用到2种情况,第一种:uni是H5形式的。第二种:uni是app形式的。都写一下。
第一种:uni H5形式的通讯。
上代码:
H5端
1.先上js加载。
2.
document.addEventListener('UniAppJSBridgeReady', function() {
document.getElementById('startsend').addEventListener('click', function() {
alert('1234')
uni.postMessage({
data: {
action: '我要传递数据,哈哈哈',
account: '375130788'
}
});
uni.getEnv(function(res) {
alert('当前环境:' + JSON.stringify(res))
});
})
});
这里,就是你的点击事件,添加发送的数据就好。
3.uni中接受数据:
mounted() {
window.addEventListener("message", this.getReceviceMsg);
},
getReceviceMsg(obj) {
console.log("H5传值为:", obj.data)
},
这个完事。就这么简单。
第二种:uni app形式的通讯。
他和H5的还不一样,真是费劲,用一样的不好吗?
1.H5页面,一样引js
2.一样,添加点击事件,发送消息
document.addEventListener('UniAppJSBridgeReady', function() {
document.getElementById('startsend').addEventListener('click', function() {
alert('1234')
uni.postMessage({
data: {
action: '我要传递数据,哈哈哈',
account: '375130788'
}
});
uni.getEnv(function(res) {
alert('当前环境:' + JSON.stringify(res))
});
})
});
3.uni webview接收,这里不一样
加上@message
reciveMessage (data) {
uni.showToast({
title: "reciveMessage 接收到消息:" + JSON.stringify(data.detail),
duration: 2000,
icon: 'none'
});
console.log("接收到消息:" + JSON.stringify(data.detail));
},
收工~~~~~
至于webview给h5传数据,就不用多说了吧。直接url后缀加参数,搞定~~~~~~
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)