解决微信公众号授权成功后返回空白页
前言 项目是用vue+vue-router
搞了好久,应该是微信授权重定向时产生一条浏览历史 ,中间怎们写都不行 以为replace不管用
permission.js 主要路由拦截
import router from './router' import { getOpenId } from './utils/auth' import { setTit } from '@/libs/util' const whiteList = ['/auth'] router.beforeEach(async(to, from, next) => { const hasOpenId = getOpenId() if (hasOpenId) { if (to.path === '/auth') { next({ path: to.query.redirect || '/' }) } else { next() } } else { if (whiteList.indexOf(to.path) !== -1) { next() } else { next({ path: `/auth?redirect=${to.path}`, replace: true }) } } }) router.afterEach((to) => {
//设置页面标题 setTit(to.meta.title || to.meta.title.zh) })
auth.js import qs from 'qs' const TokenKey = 'xgtoon-openid' export function getOpenId() { return sessionStorage.getItem(TokenKey) } export function setOpenId(token) { return sessionStorage.setItem(TokenKey, token) } export function removeOpenId() { return sessionStorage.removeItem(TokenKey) } const authUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?' const geAuthQuery = function(redirect_uri) { return { appid: process.env.VUE_APP_WEB_APPID, redirect_uri, response_type: 'code', scope: 'snsapi_base', state: 'STATE#wechat_redirect' } } export const geAuthUrl = function(url) { return `${authUrl}${qs.stringify(geAuthQuery(url))}` }
auth.vue <template> <div /> </template> <script> import { geAuthUrl, setOpenId } from '../utils/auth' import { getQueryString } from '@/libs/util' export default { data() { return { redirect: undefined } }, watch: { $route: { handler: function(route) { const query = route.query if (query) { this.redirect = query.redirect } }, immediate: true } }, created() { const code = getQueryString('code') if (!code) { const url = window.location.href window.location.replace(geAuthUrl(url)) } else { setOpenId(code) //这里就是返回空白页 this.$router.go(-1) } }, mounted() { //ios下返回做下刷新{很重要} window.addEventListener('pageshow', function(e) { // 通过persisted属性判断是否存在 BF Cache if (e.persisted) { window.location.reload() } }) } } </script> <style> </style>