How can I prevent the browser's default history back action for the backspace button with JavaScript?
You don't need return false
or e.stopPropagation()
; neither will make any difference in a listener attached with addEventListener
. Your code won't work in Opera, which only allows you to suppress the default browser behaviour in the keypress
event, or IE <= 8, which doesn't support addEventListener
. The following should work in all browsers, so long as you don't already have keydown
and keypress
event handlers on the document
.
EDIT: It also now filters out events that originated from an <input>
or <textarea>
element:
function suppressBackspace(evt) {
evt = evt || window.event;
var target = evt.target || evt.srcElement;
if (evt.keyCode == 8 && !/input|textarea/i.test(target.nodeName)) {
return false;
}
}
document.onkeydown = suppressBackspace;
document.onkeypress = suppressBackspace;