Solution to Browser Back Button Click Event Handling in JavaScript

Introduction

In JavaScript, an onbeforeunload event is fired when the page is about to unload, and there can be multiple reasons for this unload. For instance, a back or forward, or refresh button is clicked, a link on the page is clicked, and so on. 

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

window.onbeforeunload = function(event) {
    if (event.target.activeElement.tagName.toLowerCase() === 'body') {
        // The user clicked the browser's back button
        alert("Browser back button is clicked.");
    }
};

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.

window.addEventListener('unload', function(event) {
    if (event.clientX < 40 && event.clientY < 0) {
        // The user clicked the browser's back button
        alert("Browser back button is clicked.");
    } else {
        // The user refreshed the page
        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.

window.addEventListener('unload', function(event) {
    if (event.currentTarget.performance.navigation.type === PerformanceNavigation.TYPE_RELOAD) {
        // The user refreshed the page
        alert("Browser refresh button is clicked.");
    } else if (event.currentTarget.performance.navigation.type === PerformanceNavigation.TYPE_BACK_FORWARD) {
        // The user clicked the browser's back button
        alert("Browser back button is clicked.");
    }
});

So, the consolidated code snippet will look as follows.

window.addEventListener('unload', function(event) {
    if (event.currentTarget.performance && event.currentTarget.performance.navigation) {
        if (event.currentTarget.performance.navigation.type === PerformanceNavigation.TYPE_RELOAD) {
            // The user refreshed the page
            alert("Browser refresh button is clicked.");
        } else if (event.currentTarget.performance.navigation.type === PerformanceNavigation.TYPE_BACK_FORWARD) {
            // The user clicked the browser's back button
            alert("Browser back button is clicked.");
        }
    } else {
        if (event.clientX < 40 && event.clientY < 0) {
            // The user clicked the browser's back button
            alert("Browser back button is clicked.");
        } else {
            // The user refreshed the page
            alert("Browser refresh 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, which cannot be handled using the code above.

In order to handle back button functionality, we need to come up with a solution that requires server-side effort together with client-side JavaScript code.

The concept is...

We will store the current page URL in a session variable (say CurrentPageURL) on a page. When moved to another page, we will get that variable value and store it in a second session variable (say PreviousPageURL) and update the CurrentPageURL session variable with a new page URL. The ASP.NET straightforward code implementation is as follows.

//ASP.NET/C# code  
 if (Session["CurrentPageURL"] != null)  
 {  
        Session["PreviousPageURL"] = Session["CurrentPageURL"];  
 }  
 Session["CurrentPageURL"] = Request.Url; 

On the client side, when the onbeforeunload event is fired, we will verify whether the JavaScript document is. referrer value is the same as that of the session variable. If the value is the same, in other words, the back button is clicked, then it will act accordingly.

function HandleBackFunctionality() {
    const previousPageURL = sessionStorage.getItem('previousPageURL');
  
    if (document.referrer === previousPageURL) {
        alert("It's a back button click...");
        // Specific code here...
    }
  
    sessionStorage.setItem('previousPageURL', window.location.href);
}

This solution works well regardless of the browser type and is simple to implement. The server-side implementation in other languages is also straightforward. Please feel free to comment and suggest a better idea (if any).

Blog- http://www.webdevelopmenthelp.net/