【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
最近项目中使用 Vue 做 SPA 页面,采用 hash 模式做页面跳转,在微信分享的时候遇到的下面两个问题:
1. 从首页访问到内页,在内页点微信分享,获取不到标题和链接,分享出去的是首页
2. 微信分享出去的页面,点击进入后再次分享,同样获取不到标题和链接
经过测试后发现:
1. 从首页到内页后分享,iOS / Android 微信 sdk 会触发 config 信息验证失败
2. 微信分享后的地址,会自动在 # 之前添加 ?from=singlemessage&isappinstalled=0 的参数,同样会导致 config 验证失败
解决方案:
一、解决首页路由到内页分享的问题:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '../pages/index.vue'
import IndexVideo from '../pages/indexVideo.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
component: resolve => require(['../pages/index'],resolve),
meta: {
title:'index'
}
}, {
path: '/index',
component: Index
},{
path: '/indexVideo',
component: IndexVideo
}
]
const router = new VueRouter({routes})
router.beforeEach(function (to, from, next) {
const agent = navigator.userAgent
const isiOS = !!agent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
// console.log(to.path + ' == ' + location.pathname)
// // HH: 修复 iOS 微信分享地址一直为首页的问题 (这种写法在 hash 模式下不生效)
// if (isiOS && (to.path !== location.pathname)) {
// location.assign(location.origin + '/#' + to.fullPath)
// } else {
// next()
// }
// HH: 在 iOS 和 Android 下面貌似都能正常工作,唯一的缺陷就是会疯狂重定向到脚本错误为止,但是返回正常
if (to.path !== location.pathname) {
location.assign(location.origin + '/#' + to.fullPath)
}
next()
// // HH: 这种方式防止疯狂路由刷新,但是会产生一次页面重新调用,返回需要点两次的缺陷
// // &replace=1 为自定义的 url 拼接参数,需要加上判断操作否则会一直刷新一直重定向
// let _href = location.origin + '/#' + to.fullPath
// if (_href.indexOf('&replace=1') <= -1) {
// window.location.href = _href+'&replace=1'
// }
// next()
})
export default router
二、解决二次分享的问题:严格匹配地址和参数,一旦发现差异立即重新跳转到严格匹配地址
// HH: 地址参数清理
const host = `${window.location.protocol}//${window.location.host}`
const url = `${host}/#/当前页面的路由地址?replace=1`
if (window.location.href !== url) {
window.location.href = url
// console.log(window.location.href)
}
来源:oschina
链接:https://my.oschina.net/u/943746/blog/3144003