uniapp 和 webview 之间的通信
1.UniAppJSBridgeReady :
这个是在引入webview的SDK之后,当webview页面被加载完成之后会触发,该事件触发表示着uniapp和webview之间的桥成功搭建,uni对象被成功的注入到当前H5的上下文中。
我们在index.html文件中将SDK引入,这里的SDK引入必须放在body标签下面。
<!DOCTYPE html>
<html lang="zh-CN"><head>...</head><body><noscript><strong>Please enable JavaScript to continue.</strong></noscript><div id="app"></div><!-- built files will be auto injected --></body><!-- uni 的 SDK --><!-- 需要把 uni.webview.1.5.6.js 下载到自己的服务器https://gitcode.net/dcloud/uni-app/-/raw/dev/dist/uni.webview.1.5.6.js--><script type="text/javascript" src="https://gitee.com/jqn-room/public-files/blob/master/app%E4%B8%8Eh5%E9%80%9A%E4%BF%A1%E3%80%90web-view%E3%80%91/sdk/uni.webview.js"></script><script>document.addEventListener('UniAppJSBridgeReady', function() {uni.webView.getEnv(function(res) {console.log('当前环境:' + JSON.stringify(res));});// uni.webView.navigateTo(...)});</script>
</html>
2: webview中可用的 uni API
3: sdk 插件js文件
4: h5向app传信息
在需要向app传递信息的h5页面中,使用sdk进行信息传递
h5.vue
onLoad(option) {postMessageWebview() // 在当前h5页面向app发送请求
},
methods: {postMessageWebview() {let webUrl = `${Config.inviteH5}operate_activity/online_model_exam/apply_model_exam?linkId=${this.linkId}mockNo=${this.mockNo}`// APP内通过web-view嵌入的h5 向app做通信,传递消息页面// webUni 是sdk的全局遍历,里面封装了很多方法if (webUni && webUni.postMessage) {console.log("发送消息给 UniApp活动首页");let summaryCont = ['紧急,参加万人模考,中考丢分风险降降降!!!', '真哥们才通知你,快来参加陕西中考万人模考大赛,我们一起并肩上高中!']// 生成1或2的随机整数let randomNumber = Math.floor(Math.random() * 2) + 1;webUni.postMessage({data: {action: 'activeShareUrl',path: webUrl,imageUrl: 'https://wwxq.wanweiedu.com/static/share_logo1.png',summary: '二轮复习前不模考=中考埋雷!', // summaryCont[randomNumber - 1],title: "陕西万人模考实时PK榜启动!",}});} else {console.error('uni.postMessage is not a function');}}}
5:app页面接收h5传递的消息
app接收信息的路由页面
<template><web-view class="webViewBox" :fullscreen="false" @message="handleMessage" :src="adInfo.link"></web-view>
</template>
<script>export default {methods: {handleMessage(event) {// uni.showToast({// title: '接收到 H5 页面的消息',// icon: 'none'// })console.log("接收到 H5 页面的消息:", event.detail.data); // 检查消息const message = event.detail.data[0];// const { action, path } = event.data;// const { action, path } = event.detail.data;console.log("最终传输 页面的参数:" + this.urlResetFun(message.path, 'navigate'))if (message.action === 'navigate') {// 跳1: 转到指定的 UniApp 页面uni.reLaunch({url: this.urlResetFun(message.path, 'navigate')});}if (message.action === 'switchTabPrepareExam') {// 跳1: 跳转到指定tabBar页面【备考规划学】uni.switchTab({url: message.path});}// 2: 返回app首页if (message.action === 'activeBack') {// 跳转到指定的 UniApp 页面uni.reLaunch({url: message.path});}// 3:分享嵌入的当前h5路由页面if (message.action === 'activeShareUrl' || message.action === 'reportShareUrl' || message.action === 'rankShareUrl') {this.shareImageUrl = message.imageUrlthis.shareUrl = message.paththis.shareTitle = message.title,this.shareSummary = message.summarythis.creatViewNvMask();}}}}
</script>
参考链接:uniapp 和 webview 之间的通信_uniapp webview通讯-CSDN博客