51

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

4

11 Answers 11

69

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

5
  • 5
    this does not distinguish between back or forward button, just popstate, wich can be both
    – Richard
    Commented Dec 22, 2013 at 12:10
  • Your code runs perfectly in desktop browser.But in mobile browser its not working properly
    – Shwet
    Commented Aug 28, 2014 at 5:37
  • 1
    But alert fire on backword and forward both, how can i detect only back click Commented Feb 10, 2016 at 5:59
  • 2
    "The 'popstate' event only works when you push something before." This is GOLDEN! There are many examples out there, but the most important bit is this exact quote! Commented Mar 8, 2019 at 10:34
  • The code as is only works once for a given page. If you add another "window.history.pushState('forward', null, './#forward');" after the alert, it keeps stopping the user from using the back button....hehe
    – davaus
    Commented Oct 25, 2019 at 3:06
17

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
}
3
  • Unless the page headers contained "no-store" or "must-revalidate" Commented Aug 2, 2020 at 14:23
  • 1
    This no longer works. perfermance.navigation.type just gives a value of 0 and has been deprecated and its alternative is not supported by all browsers.
    – teh_ouj
    Commented Oct 6, 2020 at 4:55
  • 1
    Thank you Hasan, It worked and That was exactly I was looking for.
    – Asif Ali
    Commented Oct 16, 2020 at 9:52
12

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:

9

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);
1
  • Works like a charm on Firefox, but for some reason it doesn't always work on Chrome :/. Any suggestions on how to improve it to work on Chrome?
    – peterPP1
    Commented Jul 8, 2020 at 14:06
6

In case of HTML5 this will do the trick

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

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

1

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);
          }
        });
    
    });
    
0

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

1
  • 1
    We need to cater all browser that doesn't support HTML5
    – Nil Pun
    Commented Jul 11, 2013 at 13:34
0

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;
            }
        };
    }
};
0

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.

-2

suppose you have a button:

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

Here the code of the backBtn method:

  function backBtn(){
                    parent.history.back();
                    return false;
                }
3
  • I do not see why @senior got down votes?? This does work! If there are something i should know please let me know. ..
    – Ingus
    Commented Jan 23, 2019 at 10:48
  • @Ingus Probably because this has nothing to do with the back navigation button of the browser itself. This is for creating a custom back button on your page.
    – DerpyNerd
    Commented May 20, 2019 at 18:29
  • This is not the back button.
    – jeffci
    Commented Aug 30, 2019 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.