我们在小程序中打开H5页面,我们可能要修改分享链接,比如如果我们的是一个分享助力的活动,需要带上分享者ID,如果是商城的话可能需要带上营销员分享ID.也就产生了在H5修改小程序分享链接的需求,怎么实现呢?
其实很简单,我们只需要在H5通知小程序然后小程序再修改分享链接分享标题就可以了。
1、小程序打开H5页面
<web-view v-if="flag" :src="url" @message="handleMessage"></web-view>
这里关键点就是@message方法,然后我们在小程序页面监听该事件,该方法只会在用户点击分享或者返回才会触发。
methods: {handleMessage:function(evt) {console.log("evt.detail",evt.detail)this.shareTitle = evt.detail.data[0].shareTitle ;this.shareUrl = evt.detail.data[0].shareUrl;}}
然后分享就可以用了
onLoad(params) {console.log("params",params)var decodedURL = decodeURIComponent(params.url);this.url = decodedURL;console.log("url",this.url)//将当前链接设置到缓存中this.flag = true;uni.showShareMenu()},// 分享到朋友圈(不生效)onShareTimeline() {return {title: this.shareTitle,path: this.shareUrl}},onShareAppMessage(res) {return {title: this.shareTitle,path: this.shareUrl}}
注:上面的分享到朋友圈没有意义,web-view页面不支持分享到朋友圈
2、H5页面
//判断是小程序环境,执行下面逻辑即可wx.miniProgram.postMessage({data: {shareTitle: "分享标题自定义",shareUrl: "/pages/h5/h5?url=https%3A%2F%2Fwww.baidu.com"}})
注,这里需要引入js
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
完成。
3、小程序打开H5的代码参考
<template><view class="all"><web-view v-if="flag" :src="url" @message="handleMessage"></web-view></view></template><script>export default {components: {},data() {return {flag: false,url:'',shareTitle:'',shareUrl:'',}},onLoad(params) {console.log("params",params)var decodedURL = decodeURIComponent(params.url);this.url = decodedURL;console.log("url",this.url)//将当前链接设置到缓存中this.flag = true;uni.showShareMenu()},onShow() {if(wx.hideHomeButton){wx.hideHomeButton();}},onReachBottom() {},// 分享到朋友圈onShareTimeline() {return {title: this.shareTitle,path: this.shareUrl}},onShareAppMessage(res) {return {title: this.shareTitle,path: this.shareUrl}},methods: {searchOrderByCarNum: function() {},//这里每次分享都会有一条新的记录,所以应该取最后一条记录handleMessage:function(evt) {console.log("evt.detail",evt.detail)this.shareTitle = evt.detail.data[0].shareTitle ;this.shareUrl = evt.detail.data[0].shareUrl;},}}</script><style scoped lang="scss"></style>
