H5端分享页面时,微信会在域名和参数间自动添加类似“?/&from=singlemessage”字段且“#”后面的字段会被删除,导致分享页面只能进入首页,例子如下:
待分享链接:https://www.example.com/#/page/details/details?id=123456
微信分享之后的链接为https://www.example.com#/?from=singlemessage
导致每次只能进入index页面;这里提供一种解决办法:前端页面中转,重定向
服务器端新建一个与index.html同级的redirect.html页面,内容如下:
<script type="text/javascript">
var url=location.href;
var targeturl=url.split("target=")[1];
//"target="后面的参数为实际页面参数
var tourl='https://www.example.cn/xxx/#'+targeturl;
location.href=tourl;
</script>
前端分享页面:
var localUrl=location.href;
//去掉链接里微信自动添加的字段
localUrl= shareUrl.replace(/&from=singlemessage/g, '');
localUrl= shareUrl.replace(/\?from=singlemessage/g, '');
//"https://www.example.cn/test/redirect.html?target="为固定样式,"target="后为页面参数
var shareUlr="https://www.example.cn/test/redirect.html?target="+localUrl.split("#")[1];
调用分享api前,需要初始化this.wx(此为自定义全局wx,所以加上了this)
关于后端接口getsignature,参考链接:
https://blog.youkuaiyun.com/tx10765/article/details/118187556
Vue.prototype.wxfn_init=function(){
var that=this;
this.wx = require('@/common/jweixin-module/jweixin-module.js');
var appid=this.appid;//公众号appid
var timestamp=JSON.stringify(parseInt(new Date().getTime()/1000));
var nonceStr=Math.random().toString(36).substr(2,15);
uni.request({//
url: "https://www.example.cn/getsignature",//从后端获取签名
method:"post",
data: {"timestamp":timestamp,"nonceStr":nonceStr,"url":location.href.split("#")[0]},
success:(data)=> {
that.wx.config({
// debug: true,
appId: that.appid, // 必填,公众号的唯一标识
timestamp: timestamp, // 必填,生成签名的时间戳
nonceStr: nonceStr, // 必填,生成签名的随机串
signature: data.data,// 必填,签名
jsApiList: ["updateAppMessageShareData","updateTimelineShareData","scanQRCode","chooseImage","getLocalImgData"] // 必填,需要使用的JS接口列表
//分别表示:朋友分享、朋友圈分享、扫码、选择图片、获取图片信息
});
}
});
}
初始化完成后即可调用相关分享API:
that.wx.updateAppMessageShareData({
title: "XXX", // 分享标题
desc: "XXX", // 分享描述
link: shareUrl, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: "https://www.example.cn/img/example/logo.jpg", // 分享图标
success: function () {}
});
欢迎指正和共同探讨。