如何在h5移动端禁止某一些页面使用虚拟返回键。

1、popstate事件

MDN上是这样介绍popstate的:
当活动历史记录条目更改时,将触发popstate事件。如果被激活的历史记录条目是通过对history.pushState()的调用创建的,或者受到对history.replaceState()的调用的影响,popstate事件的state属性包含历史条目的状态对象的副本。
需要注意的是调用history.pushState()或history.replaceState()不会触发popstate事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back()或者history.forward()方法)
不同的浏览器在加载页面时处理popstate事件的形式存在差异。页面加载时Chrome和Safari通常会触发(emit )popstate事件,但Firefox则不会。
我负责的一个项目中,在微信公众号网页的某一个页面需要禁止使用微信浏览器的返回键。

2、解决方式:

点我展示代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 在禁止返回的组件的methods中写一个方法forbidBack
forbidBack(){
window.history.pushState("forward",null,"#");
window.history.forward(1);
}

// 监听返回键,禁止返回之前的路由
if(window.history && window.history.pushState){
window.addEventListener("popstate",this.forbidBack,false);
this.forbidBack();
}

//离开页面需要销毁监听
window.removeEventListener("popstate",this.forbidBack,fasle);