Search code examples
javascriptinternet-explorersharepoint-2010

Prevent backspace button from navigating back in Sharepoint 2010 and IE


As a user requirement I have to disable the backspace button from navigating back in the history. I made the following piece of code

   //Bind back nutton to prevent escaping the page with backspace
$j(document).unbind('keydown').bind('keydown', function (event) {
  var doPrevent = false;

  if (event.keyCode === 8) 
  {
      if(event.target == document.body){
          if(event.preventDefault()){ event.preventDefault(); }
          event.stopEvent();
          event.returnValue = false;
      }
  }
});

This is working perfectly in all the browsers except IE7 and IE8. I cannot bind the input types as exceptions because the content editor in SharePoint allows modification of the text in the elements div, paragraph, etc. The solution is not working in IE8 because the event.target returns the element that is on mouseover when there are no controls that have the focus.


Solution

  • Solved by myself, case closed.

    EDIT: Working in 2012 with SharePoint 2010 and jquery 1.x, not sure about today.

    //Bind back button to prevent escaping the page with backspace
    $(document).unbind('keydown').bind('keydown', function (event) {
        if (event.keyCode === 8) 
        {
         var doPrevent = true;
         //Chrome, FF, Safari
         if(event.target == document.body){
          doPrevent = true;
         }
         //IE
         else
         {
          var nodeName = event.target.nodeName.toLowerCase();
          if((nodeName == "input" && event.target.type == "text") || nodeName == "textarea")
          {
           doPrevent = false;
          }
          var SPEditTabInstance = $(document).find("li[id='Ribbon.EditingTools']");
          if(SPEditTabInstance != "undefined" && SPEditTabInstance != null && $(SPEditTabInstance).children().length > 0){
           doPrevent = false;
          }
         }
    
         if(doPrevent)
         {
          //Chrome, FF, Safari
          if(event.preventDefault()){ event.preventDefault(); }
          //IE
          else
          {
           event.returnValue = false;
          }
         }
        }
    });