- 监听popstate事件,这个对应着微信浏览器左上方后退按钮。(用得最多)
// 添加退后事件
window.addEventListener('popstate', () => {
......
// do something
......for example
// location.href = window.location.href; // 在这里指定其返回的地址,这里默认重新刷新当前页面
});
- 监听beforeunload事件,关闭或者刷新都会触发(一般不会用到)
window.addEventListener("beforeunload", function(event) {
event.returnValue = "我在这写点东西...";
});
- 特殊情况:微信浏览器左上角是X关闭,但是部分安卓手机能右滑后退,不过怎么滑都后退不了当前页面,(有的安卓手机右滑是直接关闭整个页面,效果等同于 WeixinJSBridge.call(‘closeWindow’) || IOS手机右滑或者点击下方白条后退键就可以正常后退,无须考虑这种特殊情况。) ,这种情况我也是最近才发现的,例如:华为 HUAWEI mate20.
/**
* 具备滑动后退功能的安卓手机不能后退到后一页
**/
let href;
if (this.localStorageService.getSession('href')) {
href = this.localStorageService.getSession('href'); // 获取上个页面的href,非核心代码
}
// 核心代码:用urlHistory的长度来进行判断,做了什么操作。
// 判断规则:进入页面之前有一个原始长度,当手右滑后退时,长度会加1,但是不会后退。
// 继续右滑,要么继续加1,要么就不变,但是都会比原始长度大。
if (this.localStorageService.getSession('hrefLength')) {
const hrefLength = this.localStorageService.getSession('hrefLength');
if (Number(hrefLength) < history.length) { // 判断
window.location.href = href;
}
}else {
this.localStorageService.setSession('hrefLength', history.length.toString()); // 把原始urlHistory长度保存起来
}
PS:方法有些取巧,如果有人有更好的方法,可以告知。谢谢~