Browser Back Button Click Event Handling in JavaScript

Normally, the onbeforeunload event is used for handling browser back button functionality as follows:

<body onbeforeunload="HandleBackFunctionality()">

 function HandleBackFunctionality()
 {
       if(window.event) //Internet Explorer
      {
           alert("Browser back button is clicked on Internet Explorer...");
       }
       else //Other browsers for example Chrome
       {
           alert("Browser back button is clicked on other browser...");
       }
 }

But there is a problem that identical events can occur once a user clicks on the refresh button of a browser. So, to grasp whether the refresh button or back button is clicked, we will use the subsequent code.

if(window.event.clientX < 40 && window.event.clientY < 0)
 {
      alert("Browser back button is clicked...");
 }
 else
 {
      alert("Browser refresh button is clicked...");
 }

The snippet of code above works well in browsers other than FireFox. For FireFox we need to apply the following check.

if (event.currentTarget.performance.navigation.type == 1)
 {
      alert("Browser refresh button is clicked...");
 }
 if(event.currentTarget.performance.navigation.type == 2)
 {
       alert("Browser back button is clicked...");
 }

So, the consolidated code snippet will look as:

function HandleBackFunctionality()
 {
     if(window.event)
    {
          if(window.event.clientX < 40 && window.event.clientY < 0)
         {
             alert("Browser back button is clicked...");
         }
         else
         {
             alert("Browser refresh button is clicked...");
         }
     }
     else
     {
          if(event.currentTarget.performance.navigation.type == 1)
         {
              alert("Browser refresh button is clicked...");
         }
         if(event.currentTarget.performance.navigation.type == 2)
        {
              alert("Browser back button is clicked...");
        }
     }
 }

The snippet of code above is beneficial in many scenarios, however there are some issues with it. For instance, navigation can be done using keyboard keys and refresh can also be done using F5 or CTRL+R that cannot be handled using the code above.

Comments

Popular posts from this blog

what is Event Cache table in sharepoint

CAML Query syntax and options in SharePoint

Change anchor link url in sharepoint calender