如何在单击浏览器后退按钮时调用事件

时间:2014-09-05 09:26:13

标签: jquery

单击浏览器后退按钮时如何调用jquery事件。我在asp.net mvc中使用单页应用程序,我想显示一个确认框,当用户按下浏览器的后退按钮时离开屏幕。如何在浏览器后退按钮上调用jquery函数。请帮忙。我已经搜索并发现推送状态事件但我在上述情况下没有得到如何使用它。

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:2)

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