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?
According to this documentation, the popstate event is not cancellable:
Specification: HTML5
Interface: PopStateEvent
Bubbles:
Yes
Cancelable: No
Target: defaultView
Default Action: None
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);
}
}