Search code examples
javascriptgoogle-chromebackspace

Debugging help needed: Prevent backspace from navigating back


I have a webapp which uses the backspace key for its own purposes. I've long had the following function, called on document.keyup, which has worked without issue for years:

function keyupKeys (evt) {
  if(this.activeElement.id == 'q') return true; //ignore input to the search box
  if(!evt) var evt = window.event;
  var code = evt.keyCode;

  //handle special keys:
  switch(code) {
    case  9: // tab
    case 39: // right arrow
      press('colon'); break;
    case 37: // left arrow
      press('colon');
      press('colon'); break;
    case 13: // enter
      press('eq'); break;
    case  8: // backspace
      press('bs'); break;
    case 46: // delete
    case 144:// numpad clear
      press('c'); break;
    case 27: // esc
      press('ac'); break;
    default: // Not a key this function handles
      return true;
  }
  return false;
};

Recently, I've discovered that Chrome in Windows and Chromium on Linux have started navigating back when backspace is pressed. This didn't used to be the case. I have yet to test other browsers.

Related questions on SO led me to modify the backspace case thus:

case  8: // backspace
  if(evt.preventDefault) evt.preventDefault();
  press('bs'); break;

However, this change had no effect. Furthermore, since the browser is navigating back, I can't use any of the debugging tools in the Javascript console, so I have no idea what's going on.

Can anyone explain what's happening and suggest a way to fix it?


Solution

  • Reading this answer made me think that the problem could be caused by calling my function on keyup rather than keydown. I distinctly remember that when I first wrote this code a long time ago I used keyup to solve some sort of problem; what it was I no longer recall. At any rate, I created the following function to be called onkeydown. It seems to have solved the problem.

    function keydownKeys(evt) {
      if(this.activeElement.id == 'q') return true; //ignore input to the search box
      if(!evt) var evt = window.event;
      var code = evt.keyCode;
      if(code == 8) {
        if(evt.preventDefault) {
          evt.preventDefault(); //kill backspace triggering back button
        }
        return false;
      }
      return true;
    }