Tower
Tower

Reputation: 102945

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.

Upvotes: 7

Views: 17579

Answers (3)

Paolo
Paolo

Reputation: 61

If you prefer to simply have the fix for yourself, without affecting other users when scripting into the web page, read below.

Here's some solutions that only change the browser you are using:
- Firefox on Linux "unmapped" the backspace behavior since 2006 so it's not affected; (at any rate, it was simply set to scroll up before then)
- Chrome has just announced that it will do the same from now on; (http://forums.theregister.co.uk/forum/1/2016/05/20/chrome_deletes_backspace/)
- Firefox on Windows can be set to ignore backspace by going into about:config and changing the backspace_action setting to 2; (http://kb.mozillazine.org/Browser.backspace_action)
- Safari ?!

Upvotes: 1

Marek Bar
Marek Bar

Reputation: 903

I found at Telerik's page script ready to use. Script blocks back button action: by clicking in browser back button and backspace on page. This script works. I'm using it in my project. http://www.telerik.com/community/code-library/aspnet-ajax/general/disable-backspace-from-master-page.aspx

Upvotes: 0

Tim Down
Tim Down

Reputation: 324727

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;

Upvotes: 13

Related Questions