0

I want to make a page (in this case view) which will show error if backspace is pressed.

This is my attempt for the backspace key:

<script type ="text/javascript">
$(document).ready(function (event) {
    if (event.keycode == 8) {
        alert("Don't go back");
        window.history.back(0);
    }
});

</script>

Its not working,

Also,I want to get hold of the browser back button, so that i can disable going back page.

any alternative will be embraced as it will save my day.

Thanks in advance.

  • Possible duplicate of [How to capture a backspace on the onkeydown event](http://stackoverflow.com/questions/2353550/how-to-capture-a-backspace-on-the-onkeydown-event) – Mehran Torki Feb 11 '16 at 10:14

2 Answers2

1

You generally can't (browser security restriction). You can tell if the user navigates away from the page (onbeforeunload, onunload fire) but you can't tell where they went unless you've set up your page to allow it.

HTML5 introduces the HTML5 History API; in conforming browsers, the onpopstate event will fire if the user navigates back to an earlier "page" on your site.

if (window.history && window.history.pushState) {

    $(window).on('popstate', function() {
      var hashLocation = location.hash;
      var hashSplit = hashLocation.split("#!/");
      var hashName = hashSplit[1];

      if (hashName !== '') {
        var hash = window.location.hash;
        if (hash === '') {
          alert('Back button was pressed.');
        }
      }
    });

    window.history.pushState('forward', null, './#forward');
  }
Samy Sammour
  • 2,298
  • 2
  • 31
  • 66
Abbas Galiyakotwala
  • 2,949
  • 4
  • 19
  • 34
  • It's getting blocked once. I want to block it whenever it clicks back button@Abbas –  Feb 11 '16 at 10:40
0

Bind it in key event

    $(document).unbind('keydown').bind('keydown', function (event) {
    var doPrevent = false;
    if (event.keyCode === 8) {
        var d = event.srcElement || event.target;
        if ((d.tagName.toUpperCase() === 'INPUT' && 
             (
                 d.type.toUpperCase() === 'TEXT' ||
                 d.type.toUpperCase() === 'PASSWORD' || 
                 d.type.toUpperCase() === 'FILE' || 
                 d.type.toUpperCase() === 'SEARCH' || 
                 d.type.toUpperCase() === 'EMAIL' || 
                 d.type.toUpperCase() === 'NUMBER' || 
                 d.type.toUpperCase() === 'DATE' )
             ) || 
             d.tagName.toUpperCase() === 'TEXTAREA') {
            doPrevent = d.readOnly || d.disabled;
        }
        else {
            doPrevent = true;
        }
    }

    if (doPrevent) {
        event.preventDefault();
    }
});