Is it possible to e.preventDefault in window.onPopState?

僤鯓⒐⒋嵵緔 提交于 2019-11-30 22:30:57

问题


Im 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.

But it doesnt 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?


回答1:


According to this documentation, the popstate event is not cancellable:

Specification: HTML5
Interface: PopStateEvent
Bubbles: Yes
Cancelable: No
Target: defaultView
Default Action: None




回答2:


First off "not possible" is never an acceptable answer.

Secondly you can compensate 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 so when people press it sometimes the popstate is triggered instead of the editor removing whatever character is to the left of the keyboard caret.

The following code (not posting dependencies here) 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.

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


来源:https://stackoverflow.com/questions/32432296/is-it-possible-to-e-preventdefault-in-window-onpopstate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!