1.思路
项目中遇到需要禁止浏览器回退的功能,大概意思为,有如下三个页面,访问顺序为页面A->页面B->页面C,现在想在页面C点击退出登录后,退出到页面A,且在页面A中禁止页面回退
首先想到的解决办法,清空history,但是代码层面做不到,放弃
因为使用vue,了解到在router中可以使用router.replace() 替换当前路由,这样在history中不会留下当前的URL,但是replace方法只能替换当前一个页面,如果这时候用户继续点击回退,还会回退到上一个页面
最终找到的解决方案为,进入页面A时,像history中push两条URL相同的记录->绑定popstate事件,如果点击页面回退到刚才手动push的第一条记录,就调用history.forward()回到当前页面,这样就能禁止在登录页面用户点击回退
<template>
</template>
<script>
export default {
created() {
if (!(window.history.state && window.history.state.target === 'Final')) {
window.history.pushState({ target: 'MeanSure', random: Math.random() }, '', window.location.href);
window.history.pushState({ target: 'Final', random: Math.random() }, '', window.location.href);
}
window.addEventListener('popstate', this.test, false);
},
beforeRouteLeave(to, from, next) {
window.removeEventListener('popstate', this.test, false);
next();
},
mounted() {
},
destroyed() {},
methods: {
test(e) {
if (e.state && e.state.target === 'MeanSure') {
// 此处可调用一些自定义的操作,例如弹窗提示之类的
window.history.forward();
}
},
},
};
</script>
2.history对象
未完待续...