Machinegon Machinegon - 5 months ago 32
Javascript Question

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.

Answer

Solved by myself, case closed, here's the solution on my blog.

http://www.dotnetmikael.com/2012/11/blocking-backspace-button-from.html

//Bind back button to prevent escaping the page with backspace
$j(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 = $j(document).find("li[id='Ribbon.EditingTools']");
      if(SPEditTabInstance != "undefined" && SPEditTabInstance != null && $j(SPEditTabInstance).children().length > 0){
       doPrevent = false;
      }
     }

     if(doPrevent)
     {
      //Chrome, FF, Safari
      if(event.preventDefault()){ event.preventDefault(); }
      //IE
      else
      {
       event.returnValue = false;
      }
     }
    }
});