[javascript] JavaScript or jQuery browser back button click detector

Could someone please share experience / code how we can detect the browser back button click (for any type of browsers)?

We need to cater all browser that doesn't support HTML5

This question is related to javascript jquery back-button

The answer is


In javascript, navigation type 2 means browser's back or forward button clicked and the browser is actually taking content from cache.

if(performance.navigation.type == 2) {
    //Do your code here
}

Hasan Badshah's answer worked for me, but the method is slated to be deprecated and may be problematic for others going forward. Following the MDN web docs on alternative methods, I landed here: PerformanceNavigationTiming.type

if (performance.getEntriesByType("navigation")[0].type === 'back_forward') {
  // back or forward button functionality
}

This doesn't directly solve for back button over the forward button, but was good enough for what I needed. In the docs they detail the available event data that may be helpful with solving your specific needs:

function print_nav_timing_data() {
  // Use getEntriesByType() to just get the "navigation" events
  var perfEntries = performance.getEntriesByType("navigation");

  for (var i=0; i < perfEntries.length; i++) {
    console.log("= Navigation entry[" + i + "]");
    var p = perfEntries[i];
    // dom Properties
    console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - 
    p.domContentLoadedEventStart));
    console.log("DOM complete = " + p.domComplete);
    console.log("DOM interactive = " + p.interactive);

    // document load and unload time
    console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
    console.log("document unload = " + (p.unloadEventEnd - 
    p.unloadEventStart));

    // other properties
    console.log("type = " + p.type);
    console.log("redirectCount = " + p.redirectCount);
  }
}

According to the Docs at the time of this post it is still in a working draft state and is not supported in IE or Safari, but that may change by the time it is finished. Check the Docs for updates.


Disable the url button by following function

window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle the back (or forward) buttons here
            // Will NOT handle refresh, use onbeforeunload for this.
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Detect and redirect change here
                // Works in older FF and IE9
                // * it does mess with your hash symbol (anchor?) pound sign
                // delimiter on the end of the URL
            }
            else {
                ignoreHashChange = false;
            }
        };
    }
};

In case of HTML5 this will do the trick

window.onpopstate = function() {
   alert("clicked back button");
}; history.pushState({}, '');

In my case I am using jQuery .load() to update DIVs in a SPA (single page [web] app) .

Being new to working with $(window).on('hashchange', ..) event listener , this one proved challenging and took a bit to hack on. Thanks to reading a lot of answers and trying different variations, finally figured out how to make it work in the following manner. Far as I can tell, it is looking stable so far.

In summary - there is the variable globalCurrentHash that should be set each time you load a view.

Then when $(window).on('hashchange', ..) event listener runs, it checks the following:

  • If location.hash has the same value, it means Going Forward
  • If location.hash has different value, it means Going Back

I realize using global vars isn't the most elegant solution, but doing things OO in JS seems tricky to me so far. Suggestions for improvement/refinement certainly appreciated


Set Up:

  1. Define a global var :
    var globalCurrentHash = null;
  1. When calling .load() to update the DIV, update the global var as well :

    function loadMenuSelection(hrefVal) {
      $('#layout_main').load(nextView);
      globalCurrentHash = hrefVal;
    }
    
  2. On page ready, set up the listener to check the global var to see if Back Button is being pressed:

    $(document).ready(function(){
      $(window).on('hashchange', function(){
          console.log( 'location.hash: ' + location.hash );
          console.log( 'globalCurrentHash: ' + globalCurrentHash );
    
          if (location.hash == globalCurrentHash) {
              console.log( 'Going fwd' );
          }
          else {
    
              console.log( 'Going Back' );
              loadMenuSelection(location.hash);
          }
        });
    
    });
    

You can use this awesome plugin

https://github.com/ianrogren/jquery-backDetect

All you need to do is to write this code

  $(window).load(function(){
    $('body').backDetect(function(){
      // Callback function
      alert("Look forward to the future, not the past!");
    });
  });

Best


Found this to work well cross browser and mobile back_button_override.js .

(Added a timer for safari 5.0)

// managage back button click (and backspace)
var count = 0; // needed for safari
window.onload = function () { 
    if (typeof history.pushState === "function") { 
        history.pushState("back", null, null);          
        window.onpopstate = function () { 
            history.pushState('back', null, null);              
            if(count == 1){window.location = 'your url';}
         }; 
     }
 }  
setTimeout(function(){count = 1;},200);

suppose you have a button:

<button onclick="backBtn();">Back...</button>

Here the code of the backBtn method:

  function backBtn(){
                    parent.history.back();
                    return false;
                }

It's available in the HTML5 History API. The event is called 'popstate'


The 'popstate' event only works when you push something before. So you have to do something like this:

jQuery(document).ready(function($) {

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

    window.history.pushState('forward', null, './#forward');

    $(window).on('popstate', function() {
      alert('Back button was pressed.');
    });

  }
});

For browser backward compatibility I recommend: history.js


there are a lot of ways how you can detect if user has clicked on the Back button. But everything depends on what your needs. Try to explore links below, they should help you.

Detect if user pressed "Back" button on current page:

Detect if current page is visited after pressing "Back" button on previous("Forward") page:


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to back-button

Android: Quit application when press back button JavaScript or jQuery browser back button click detector Clicking the back button twice to exit an activity How to exit from the application and show the home screen? Android - How To Override the "Back" button so it doesn't Finish() my Activity? Preventing iframe caching in browser How to exit when back button is pressed?