Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an event when browser back button is clicked

Tags:

jquery

How to call a jquery event when browser back button is clicked. I am using a single page application in asp.net mvc and i want to show a confirm box to leave the screen when user press the back button of the browser. How can i call a jquery function on browser back button. Please help. I have searched and found push state event but i did not get how to use it in my case described above.

like image 388
Ankit Sahrawat Avatar asked Sep 05 '14 09:09

Ankit Sahrawat


2 Answers

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

  }
});

JavaScript or jQuery browser back button click detector

like image 173
Charles-Antoine Fournel Avatar answered Oct 19 '22 06:10

Charles-Antoine Fournel


window.userInteractionTimeout = null;
window.userInteractionInHTMLArea = false;
window.onBrowserHistoryButtonClicked = null; // This will be your event handler for browser navigation buttons clicked

$(document).ready(function () {
    $(document).mousedown(function () {
        clearTimeout(window.userInteractionTimeout);
        window.userInteractionInHTMLArea = true;
        window.userInteractionTimeout = setTimeout(function () {
            window.userInteractionInHTMLArea = false;
        }, 500);
    });

$(document).keydown(function () {
        clearTimeout(window.userInteractionTimeout);
        window.userInteractionInHTMLArea = true;
        window.userInteractionTimeout = setTimeout(function () {
            window.userInteractionInHTMLArea = false;
        }, 500);
    });

    if (window.history && window.history.pushState) {
        $(window).on('popstate', function () {
            if (!window.userInteractionInHTMLArea) {
                // alert('Browser Back or Forward button was pressed.');
                 }
    if(window.onBrowserHistoryButtonClicked ){
    window.onBrowserHistoryButtonClicked ();
            }
        });
    }
});
like image 2
Varun Avatar answered Oct 19 '22 07:10

Varun