赞
踩
uni-app中的web-view是一个 web 浏览器组件,可以用来承载网页的容器,uni-app开发的app与web-view实现交互的方式相关简单,应用通过属性@message绑定触发事件,然后在web-view的网页向应用 postMessage 触发并收到消息即可,详细请参考官网:web-view | uni-app官网 (https://uniapp.dcloud.net.cn/component/web-view.html#)主要实现代码参考下图所示。
<template> <web-view :src="url" @message="handleMessage"></web-view> </template> <script> export default { data() { return { url: null //要打开的外部链接 }; }, methods: { //通过 @message 事件接收外部链接传过来的内容 handleMessage(event) { if (event.detail.data[0].isClose) { uni.reLaunch({ url: '/main/main' }); } } } }; </script>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>我是在app里打开的页面</title> <script src="./jquery-3.4.1.js" type="text/javascript" charset="utf-8"></script> <!-- 微信JS-SDK 兼容微信小程序 引入此文件 --> <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script> <!-- uni-app SDK --> <script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script> </head> <body> <div style="width: 100%;height: 100%;position: absolute;left: 0;top: 0;right: 0;bottom: 0;"> <button id="btn">按钮</button> </div> </body> <script> document.addEventListener('UniAppJSBridgeReady', function() { console.log("加载完成,可以使用uni相关接口"); }); $("#btn").click(function() { uni.postMessage({ data: { isClose: true } }) uni.navigateBack(); }) </script> </html>
但是,以上方法只适合于APP,在H5环境中是不支持的,官方说明如下:
那么,在uni-app如何实现在H5环境中与web-view中的网页交互通讯呢,按照官方的说法,使用window.postMessage方式实现!
关于window.postMessage的通讯原理,请参考官方档window.postMessage - Web API 接口参考 | MDN(https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage)
onLoad: function() {
window.addEventListener('message', function(e) { // 监听 message 事件
console.log(e.origin);
console.log("从" + e.origin + "收到消息: " + e.data);
});
}
//向uniapp发送信息
function sendMsgToUniapp(value) {
parent.postMessage(value, "*");
}
说明:uni-app的web-view,在H5环境中其实就是通过iframe来实现的,因此在iframe中的页面可直接通过jquery中的parent来获取父页面对象,并通过parent.postMessage的方式传递消息。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。