在小程序里使用web-view組件,在對小程序點擊頂部分享按鈕分享時,分享的內容為當前頁面的內容,需要使用wx.miniProgram.postMessage來進行處理
H5頁面代碼
created() { this.$store .dispatch({ type: "user/saveCurrentUrl", data: { current_url: window.location.pathname + window.location.search, page_type: "3" } }) .then(res => { if (res.code == 1) { window.wx.miniProgram.postMessage({ data: { title: res.data.title, // 標題 desc: "", // 描述 imgUrl: "", // 圖片 link: res.data.url, // 鏈接 unique_mark: res.data.unique_mark } }); } }); let id = this.$route.params.id; let activityId = this.$route.query.activityId; this.getActivityProductDetail(id, activityId); }
小程序端代碼
<web-view src='{{weburl}}' bindmessage="getSharePage"></web-view>
onShareAppMessage: function() { let _this = this; let title = "發現一件好物"; if (app.globalData.shopname) { title = app.globalData.shopname; } console.log(this.data.sharePageModel); let path = "pages/index/index"; if (this.data.sharePageModel) { path += "?share_openid=" + app.globalData.openid + "&unique_mark=" + this.data.sharePageModel.unique_mark; title = this.data.sharePageModel.title; } return { title: title, path: path, success: _suc => { wx.showToast({ title: '分享成功', }) }, fail: _fail => { wx.showToast({ title: '分享失敗', }) } }; }, getSharePage: function(e) { console.log("獲取網頁內容"); console.log(e); if (e && e.detail && e.detail.data) { let len = e.detail.data.length; this.setData({ sharePageModel: e.detail.data[len - 1] }); } },
調試截圖
注意點:wx.miniProgram.postMessage該方法的使用有條件,小程序分享、銷毀等都會執行,H5頁面每執行一次,會在小程序端記錄一條數據(數組形式),我目前做的是用戶分享時取的是數組下標最大的,但是也存在一個缺陷,當H5頁面未設置分享參數,而用戶點擊了頂部分享操作,分享數據將取最后一條,目前還在處理中(每個H5頁面加上分享postMessage感覺不現實),求招...