Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent the browser's default history back action for the backspace button with JavaScript?

Is there a way to prevent the default action from occurring when the user presses backspace in a browser?

I don't need to prevent the user from leaving, just from having the default backspace action. I need the backspace to do something different (it's a game).

I tried without success:

window.addEventListener('keydown', function(e) {
    if (e.keyCode === Game.Key.BACK_SPACE)
    {
        e.preventDefault();
        e.stopPropagation();
        return false;
    }
}, false);

If I put an alert inside the if, the alert will be shown for backspace key press. So, the keyCode is correct.

This has to work in Opera 10.6, Firefox 4, Chrome 6, Internet Explorer 9 and Safari 5.

like image 968
Tower Avatar asked Oct 03 '10 15:10

Tower


People also ask

How do I restrict Backspace in JavaScript?

Use the onkeydown event and preventDefault() method to Disable Backspace and Delete key in JavaScript. Backspace char code is 8 and deletes key char code is 46.

Is it possible to disable browser back button?

You can-not actually disable the browser back button. However, you can do magic using your logic to prevent the user from navigating back which will create an impression like it is disabled.

How do I disable the Back button in Chrome?

Select Settings from the list. Scroll down to the Privacy and Security section, and select the Site settings from the menu. Choose the Pop-ups and redirects option within Site settings. Toggle the button to turn OFF and block the pop-ups and redirection.


1 Answers

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;
like image 91
Tim Down Avatar answered Sep 21 '22 23:09

Tim Down