有个需求,vue页面。 页面首次打开会隐式登录,然后跳转微信获取code之后会重新回到页面。
但是微信浏览器中history会缓存未登录前页面。用户按返回按钮会返回过来。项目中未登录的页面不显示,所有会出现空白页面。查看资料后解决了
mounted() {
// 监听返回事件 如果出现唯一标识 调用微信sdk 关闭当前页面
window.addEventListener(
'popstate',
function(e) {
if (window.location.hash == '#close') {
wx.closeWindow()
}
},
false
)
// 首次打开页面 给地址栏添加唯一标识
function pushHistory() {
var state = {
title: window.document.title,
url: '#'
}
window.history.pushState(state, window.document.title, '#close')
}
const that = this
// 获取保存的登录标识
this.implicit = sessionStorage.getItem('implicit') || false
// 隐式登录过 不再执行隐式登录
if (this.implicit) {
return false
}
// 隐式登录
const okurl = window.location.pathname + window.location.search
const redirectUrl =
window.location.origin + '/auth?baseUrl=' + encodeURIComponent(okurl)
// 已经获取了当前地址(没有#close),然后再调用pushHistory,把地址栏添加唯一标识#close
pushHistory()
// 调用接口跳转微信授权登录
this.$request
.post(api.h5ImplicitAuth_api, { redirectUrl })
.then(function(res) {
sessionStorage.setItem('implicit', 1)
window.location.replace(res)
})
.catch(function(error) {
sessionStorage.setItem('implicit', 1)
that.implicit = true
console.log('error', error)
})
}