How to prevent replay of default browser history for backspace button with javascript?

Is there a way to prevent the default action when the user clicks the backspace button in the browser? I don't need to keep the user from leaving, just because of the default backspace action. I need backspace to do something else (this is 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 a warning inside if, a warning will appear for pressing the backspace key. So, keyCode is correct.

Edit: this should work in Opera 10.6, Firefox 4, Chrome 6, IE 9, and Safari 5.

+6
javascript events
03 Oct 2018-10-10
source share
3 answers

You do not need return false or e.stopPropagation() ; neither one nor the other will have anything to do with the listener attached to addEventListener . Your code will not work in Opera, which allows you to disable the default browser behavior in the keypress or IE <= 8 event, which addEventListener does not support. The following should work in all browsers if you don't already have keydown and keypress event handlers on document .

EDIT . It also now filters out events created 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; 
+12
03 Oct 2018-10-10
source share

I found a script ready to use on the Telerik page. The script blocks the action of the Back button: by clicking the Back Back and Back buttons on the page. This script is working. I use it in my project. http://www.telerik.com/community/code-library/aspnet-ajax/general/disable-backspace-from-master-page.aspx

0
Jul 31. '13 at 21:18
source share

If you would rather just fix yourself without affecting other users when writing scripts on a web page, read below.

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

0
May 20 '16 at 10:38
source share



All Articles