一个基于uniapp写的小程序,改为h5之后,在微信公众号里进行分享,然后经过一系列步骤终于实现了
步骤一、实现微信jsapi里关于分享的步骤
个人实现后的理解:每次进入页面时,先把本页面分享的信息(标题,描述,图片)准备好,传给config。(config里会调用后台方法,后台会调微信接口生成签名)。
wechat.js
// wechat.js
// 初始化sdk配置
initJssdk: function(callback) {
console.log('url', window.location.href)
console.log('callback', callback)
if (this.isWechat()) {
var url = window.location.href //.split('#')[0]
getShareInfoForWeixinH5({
url: url
}).then(res => {
console.log('getShareInfoForWeixinH5 --- res', res)
var share = res.data.data
console.log('share info ---', share)
jweixin.config({
debug: share.debug || this.debug,
appId: share.appId,
timestamp: share.timestamp,
nonceStr: share.nonceStr,
signature: share.sign,
jsApiList: share.jsApiList || this.jsApiList
})
if (typeof callback === 'function') {
callback(share)
}
})
}
},
// 微信分享
share: function(data, callback) {
console.log('share', data)
if (this.isWechat()) {
this.initJssdk(function(init) {
console.log('init ', init)
jweixin.ready(function() {
var url = window.location.href // .split('#')[0]
var shareData = {
title: data.title,
desc: data.desc,
link: url,
imgUrl: data.image,
success: function(res) {
callback(res)
},
cancel: function(res) {
callback(res)
}
}
jweixin.updateAppMessageShareData(shareData)
jweixin.updateTimelineShareData(shareData)
})
})
}
},
进入页面时初始化分享设置
onLoad(e) {
this.initShareApp(goods)
}
methods: {
initShareApp(goods) {
var param = {
title: goods.title,
desc: goods.title,
image: goods.image
}
console.log('share param', param)
console.log('share url ', window.location.href)
if (this.$wechat && this.$wechat.isWechat()) {
this.$wechat.share(param)
}
},
main.js
// #ifdef H5
import wechat from './api/wechat.js'
Vue.prototype.$wechat = wechat
// #endif
然后用户从微信网页的右上方三个点的地方打开,转发朋友,分享朋友圈,就会触发预制的分享方法,该方法就会用提前准备好的分享的信息(标题,描述,图片)把当前页面+链接分享出去。
步骤二、因为jsapi不支持url里的#,把路由模式改为history模式
基于uniapp的前端工程,打包配置修改 vue.config.js 不起作用,还是要修改manifest.json
步骤三、改为history模式后,nginx需要配置rewrite,这里是k8s-rancher-ingress
list
h5:rules
h5:Ingress Class
h5:Annotations
h5:nginx.ingress.kubernetes.io/rewrite-target /h5/index.html
h5/*.png .css .js 等:
Rules
/h5/(.*)(\.)(gif|jpg|jpeg|png|bmp|swf|css|js|eot|svg|ttf|woff|woff2|properties|json)$
Ingress Class
nginx
Annotations
nginx.ingress.kubernetes.io/rewrite-target /h5/$1$2$3
nginx.ingress.kubernetes.io/use-regex true
步骤四、测试时,发现了history模式下请求地址的规律
首页地址改为
/h5/pages/index/index