在小程序里使用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感觉不现实),求招...