Tuesday, 30 December 2014

JavaScript that disables "browser back" functionality

Here the code, note that "addEventListener" works only from IE9, if you need also support of earlier IE, just change "addEventListener" to the "onkeydown" event.

  var handleBackSpace = function handleBackSpaceFunction(evt) {  
    switch (evt.target.tagName.toLowerCase()) {  
       case "input":  
         if (evt.target.type.toLowerCase() == "text" || evt.target.type.toLowerCase() == "password") {  
            disableIfNeeded(evt);  
            break;  
            //case of checkboxes  
         } else {  
            evt.preventDefault();  
         }  
       case "textarea":  
         disableIfNeeded(evt)  
         break;  
       default:  
         disableBackspace(evt)  
         break;  
    }  
  }  
  document.addEventListener('keydown', handleBackSpace, false);  
  function disableIfNeeded(evt) {  
    if (evt.target.readOnly == true) {  
       evt.preventDefault();  
    }  
  }  
  function disableBackspace(evt) {  
    var key;  
    if (typeof evt.keyIdentifier !== "undefined") {  
       key = evt.keyIdentifier;  
    } else if (typeof evt.keyCode !== "undefined") {  
       key = evt.keyCode;  
    }  
    if (key === 'U+0008' ||  
       key === 'Backspace' ||  
       key === 8) {  
       evt.preventDefault();  
    }  
  }  

No comments:

Post a Comment