javascript 是否可以在 window.onPopState 中使用 e.preventDefault?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32432296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to e.preventDefault in window.onPopState?
提问by phoenix
I'm trying to stop the user from going back in my web app. For this I tried catching the window.onpopstate
and added e.preventDefault
to cancel the back button effect.
我试图阻止用户返回我的网络应用程序。为此,我尝试捕捉window.onpopstate
并添加e.preventDefault
以取消后退按钮效果。
But it doesn't seems to happen.
但这似乎不会发生。
window.addEventListener('popstate',function(e){
console.log(e); e.preventDefault();
});
Is it not possible to prevent the popstate
event of browser? Or am I doing something wrong?
popstate
浏览器的事件是不是不能阻止?还是我做错了什么?
回答by Patrick Klug
According to this documentation, the popstate event is not cancellable:
根据此文档,popstate 事件不可取消:
Specification: HTML5
Interface: PopStateEvent
Bubbles: Yes
Cancelable: No
Target: defaultView
Default Action: None
规范:HTML5
接口:PopStateEvent
气泡:是
可取消:否
目标:defaultView
默认操作:无
回答by John
First off "not possible" is never an acceptable answer.
首先,“不可能”从来都不是一个可以接受的答案。
Secondly you cancompensate for popstate bugs. In example my rich editor has to constantly compensate for the lazy-bastard key: Backspace. It's not a valid key for a back button (just like spacebar for "page downing") but people impose their personal preferences upon the world instead of adding a browser extension sowhen people press it sometimes the popstate is triggered instead of the editor removing whatever character is to the left of the keyboard caret.
其次,您可以补偿 popstate 错误。例如,我的富编辑器必须不断补偿懒惰的混蛋键:退格键。它不是后退按钮的有效键(就像“翻页”的空格键一样),但人们将他们的个人偏好强加于世界而不是添加浏览器扩展,因此当人们按下它时,有时会触发 popstate 而不是编辑器删除任何内容字符位于键盘插入符号的左侧。
The following code (dependencies in my platform's documentation) detects when the popstate bug is triggered, slaps it in the face with a e.preventDefault();
and then fixes the address bar address with history.go(1);
. The person using the editor doesn't notice anything happened as the browser was not allowed to manipulate the DOM. This code is minimal (other people may be compensating for this bug in various contexts) and I've only tested this in Gecko/Firefox currently so be sure to test Blink, Presto, Trident and WebKit based browsers as well.
以下代码(我平台文档中的依赖项)检测 popstate 错误何时触发,用 a 拍打它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);
}
}