是否可以在window.onPopState中e.preventDefault?

问题描述 投票:0回答:3

我试图阻止用户返回我的网络应用程序。为此,我尝试捕获

window.onpopstate
并添加
e.preventDefault
来取消后退按钮效果。

但这似乎并没有发生。

window.addEventListener('popstate',function(e){ 
console.log(e); e.preventDefault();  
});

是否无法阻止浏览器的

popstate
事件?还是我做错了什么?

javascript dom-events back-button popstate
3个回答
38
投票

根据此文档,popstate事件不可取消:

规范:HTML5
接口:PopStateEvent
气泡: 是的
可取消:否
目标:defaultView
默认操作:无


8
投票

首先“不可能”永远不是一个可以接受的答案。

其次,你可以弥补 popstate 的错误。例如,我的富编辑器必须不断地补偿懒惰的混蛋键:退格键。它不是后退按钮的有效键(就像用于“页面向下”的空格键),但人们将自己的个人偏好强加于世界,而不是添加浏览器扩展so当人们按下它时,有时会触发 popstate 而不是编辑器删除键盘插入符号左侧的任何字符。

下面的代码(依赖于我的平台文档)检测popstate错误何时被触发,用

e.preventDefault();
打它的脸,然后用
history.go(1);
修复地址栏地址。使用编辑器的人不会注意到发生了任何事情,因为浏览器不允许操作 DOM。这段代码是最少的(其他人可能会在各种情况下补偿这个错误),我目前只在 Gecko/Firefox 中测试过这个,所以一定要测试基于 Blink、Presto、Trident 和 WebKit 的浏览器。

window.onpopstate = function(e)
{
 if (id_('editor') && is_node_parent(document.activeElement,id_('editor')))
 {
  e.preventDefault();
  history.go(1);
 }
}

0
投票

嗯,可能没有正常的方法可以实现这一点,但是有一些技巧。

这个就可以了!

// Sets up three history items and places the user in the middle of those three.
window.history.pushState({ _fileexplorer: "back" }, document.title);
window.history.pushState({ _fileexplorer: "main" }, document.title);
window.history.pushState({ _fileexplorer: "forward" }, document.title);
window.history.back();

// Capture browser-level back/forward buttons. Alters browser history.
window.addEventListener("popstate", (ev) => {
  if (ev.state && ev.state._fileexplorer) {
    if (ev.state._fileexplorer === "back")
      window.history.forward();
    else if (ev.state._fileexplorer === "forward")
      window.history.back();
  }
}, true);

但是这样你的浏览器历史记录就会变得混乱

我最初的答案是取消按钮事件,最终在

Brave
中工作,但在
Vivaldi

中不起作用
window.addEventListener("mouseup", (ev) => {
  if (ev.button === 3) {
    ev.preventDefault();
  }
});

附注我也是小白,欢迎指正

© www.soinside.com 2019 - 2024. All rights reserved.