微信环境下安卓,ios浏览器历史栈有区别h5页面
在安卓系统无法使用以下方法修改浏览器历史记录
window.history.pushState()
所以无法通过以下方法监听浏览器返回事件
window.addEventListener('popstate', closeWindow, false)
function closeWindow () {
if (wx.closeWindow) {
wx.closeWindow()
} else {
WeixinJSBridge.call('closeWindow')
}
window.removeEventListener('popstate', closeWindow ,false)
}
ios系统可以使用上面的相关方法
安卓系统点击返回直接返回对话框
鉴于上述方法无法使用所以使用了第二套方案解决问题
let openId = sessionStorage.getItem('openId') || ''
let backOpenId = getQueryString('openId') || '
if (isWechat == 'wechat') {
if(!openId && !backOpenId) {
window.location.href = window.location.origin + '/security-service/api/wechat/oauth2/authorize?returnUrl=' + encodeURIComponent(window.location.href);;
return false;
}
if (isAndroid && !openId && backOpenId) {
sessionStorage.setItem('openId', backOpenId)
window.history.go(-window.history.length + 1)
return false
} else {
window.history.pushState(null, null, window.location.href)
}
}
function getQueryString(name) {
let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
let r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}
基于以上代码实现了安卓,ios返回事件退回微信对话框。
有更好的方案,欢迎一起讨论