0

Does anyone know how to disable the ability to use the "backspace" key on your keyboard to navigate to the previous page you were on?

Right now, I have an invoice type web application, that if the user(on a mac) hits backspace to remove an element within a form field, after reaching the end of the entered item, if they hit the backspace again, it moves to the prior browsed page, making them lose data with the application that was entered.

mason
  • 31,774
  • 10
  • 77
  • 121
Steven
  • 687
  • 1
  • 10
  • 27

2 Answers2

7
window.onkeydown = function(e) {
  if (e.keyCode == 8 && e.target == document.body)
    e.preventDefault();
}

Explanation: The backspace key has keycode 8. Calling "preventDefault" means that the event does not cause the default behaviour of pressing the backspace key (i.e. navigating back a page). This behaviour only happens if the target of the event is the document's body.

Edit: jsfiddle example

Sam
  • 3,070
  • 3
  • 20
  • 26
  • do I just add that in a – Steven Aug 27 '15 at 20:02
  • 2
    This interferes with backspacing in a text box. My understanding of the question is that Steven is only trying to prevent backspace being used to navigate backwards in the page stack, but that other uses of backspace should be allowed. – mason Aug 27 '15 at 20:04
  • 2nd the above comment, I want users to still be able to use backspace, just not be able to navigate away from page using backspace... – Steven Aug 27 '15 at 20:05
  • There you go - now it will allow you to use the backspace key as normal. This should go in a – Sam Aug 27 '15 at 20:06
2

The downside to @Sam's answer is that if you click on an HTML element, such as a table, the Backspace key still takes you back. It only works if you click in a "clear space" that does not have any HTML elements.

I tweaked Sam's answer and took code from this answer to create this solution. It does not cover all edge cases, but it was enough for my use case.

function disableBackspaceNavigation() {
  window.onkeydown = function(e) {
    if (e.keyCode == 8 && !isTextBox(e.target)) e.preventDefault();
  }
}

function isTextBox(element) {
  var tagName = element.tagName.toLowerCase();
  if (tagName !== "input") return false;

  var typeAttr = element.getAttribute('type').toLowerCase();
  return typeAttr === 'text';
}
Michael
  • 34,873
  • 17
  • 75
  • 109