detect back button click in browser

JavascriptJquery

Javascript Problem Overview


I have to detect if a user has clicked back button or not. For this I am using

window.onbeforeunload = function (e) {
}

It works if a user clicks back button. But this event is also fired if a user click F5 or reload button of browser. How do I fix this?

Javascript Solutions


Solution 1 - Javascript

So as far as AJAX is concerned...

Pressing back while using most web-apps that use AJAX to navigate specific parts of a page is a HUGE issue. I don't accept that 'having to disable the button means you're doing something wrong' and in fact developers in different facets have long run into this problem. Here's my solution:

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

As far as Ive been able to tell this works across chrome, firefox, haven't tested IE yet.

Solution 2 - Javascript

Please try this (if the browser does not support "onbeforeunload"):

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

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

    $(window).on('popstate', function() {
      var hashLocation = location.hash;
      var hashSplit = hashLocation.split("#!/");
      var hashName = hashSplit[1];

      if (hashName !== '') {
        var hash = window.location.hash;
        if (hash === '') {
          alert('Back button was pressed.');
        }
      }
    });

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

});

Solution 3 - Javascript

best way I know

         window.onbeforeunload = function (e) {
		    var e = e || window.event;
		    var msg = "Do you really want to leave this page?"
		   
		    // For IE and Firefox
		    if (e) {
		        e.returnValue = msg;
		    }
		
		    // For Safari / chrome
		    return msg;
         };

Solution 4 - Javascript

I'm detecting the back button by this way:

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

It works but I have to create a cookie in Chrome to detect that i'm in the page on first time because when i enter in the page without control by cookie, the browser do the back action without click in any back button.

if (typeof history.pushState === "function"){
history.pushState("jibberish", null, null); 
window.onpopstate = function () {
	if ( ((x=usera.indexOf("Chrome"))!=-1) && readCookie('cookieChrome')==null ) 
	{
		addCookie('cookieChrome',1, 1440);      
	} 
	else 
	{
		history.pushState('newjibberish', null, null);	
	}
};

}

AND VERY IMPORTANT, history.pushState("jibberish", null, null); duplicates the browser history.

Some one knows who can i fix it?

Solution 5 - Javascript

Since the back button is a function of the browser, it can be difficult to change the default functionality. There are some work arounds though. Take a look at this article:

http://www.irt.org/script/311.htm

Typically, the need to disable the back button is a good indicator of a programming issue/flaw. I would look for an alternative method like setting a session variable or a cookie that stores whether the form has already been submitted.

Solution 6 - Javascript

I'm assuming that you're trying to deal with Ajax navigation and not trying to prevent your users from using the back button, which violates just about every tenet of UI development ever.

Here's some possible solutions: JQuery History Salajax A Better Ajax Back Button

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfacebookView Question on Stackoverflow
Solution 1 - JavascriptGus CrawfordView Answer on Stackoverflow
Solution 2 - JavascriptBenny NeugebauerView Answer on Stackoverflow
Solution 3 - JavascriptMarco AlloriView Answer on Stackoverflow
Solution 4 - JavascriptAlexandraView Answer on Stackoverflow
Solution 5 - JavascriptJames HillView Answer on Stackoverflow
Solution 6 - Javascriptbpeterson76View Answer on Stackoverflow