<script type="text/javascript" src="//res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
var ua = window.navigator.userAgent.toLowerCase(); if (ua.indexOf("miniprogram") != -1 && wx.miniProgram) { wx.miniProgram.getEnv(function (res) { if (res.miniprogram) { // 小程序环境下逻辑 var title = document.title; var desc = getDesc(); if (!desc || desc == "") { desc = "天下网吧是最早最权威的网吧门户站,为网吧业主和相关人员提供网吧和网咖的技术,网吧联盟,经营,管理,网吧系统,无盘网吧,主页,网吧影视,收费,网吧软件,以及网吧论坛交流服务为主的行业第一站"; } console.log("postMessage",title); console.log("postMessage",desc); wx.miniProgram.postMessage({ data: { title: title, desc: desc, } }); } else { //非小程序环境下逻辑 } }) }
其中,getDesc是获取页面<meta name="Description"的值的。可以自行编写或者直接写死。
小程序Webview页面里面接收H5页面Post过来的Message。wxml绑定相关事件:
<view class="pageH5" style='padding-top:-200px;'> <web-view src="{{url}}" bindmessage="h5PostMessage" binderror="onerror" bindload="bindload"></web-view> </view>webview的JS里面编写h5PostMessage方法
//h5向小程序发送的数据 h5PostMessage: function (e) { this.h5Data = e.detail.data; this.setData({ h5Data: e.detail.data, }); if (this.data.h5Data.length > 0) { this.setData({ h5Data: this.data.h5Data[this.data.h5Data.length-1], }); } },
小程序的webview页面转发时设置分享标题和其他数据:
onShareAppMessage(options) { console.log("this.h5Data", this.data.h5Data); //options.webViewUrl 可获得当前url var shareurl = '/pages/web/web?url=' + encodeURIComponent(options.webViewUrl); var that = this; console.log("this.data.h5Data", this.data.h5Data.title); var tmpstr = that.data.h5Data.title ? that.data.h5Data.title : that.data.webtitle; console.log(tmpstr); return { title: tmpstr ? tmpstr : "天下网吧分享干货给您", path: shareurl, desc: that.data.h5Data.desc?that.data.h5Data.desc:'天下网吧、网咖天下', success: function (res) { // 转发成功 console.log(res) wx.showToast({ title: '分享成功', icon: 'success', duration: 2000 }) }, fail: function (res) { // 转发失败 wx.showToast({ title: '分享失败', icon: 'fail', duration: 2000 }) } } },