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

Ank*_*wat 5 jquery

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

Cha*_*nel 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.');
    });

  }
});
Run Code Online (Sandbox Code Playgroud)

JavaScript或jQuery浏览器后退按钮点击检测器


小智 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 ();
            }
        });
    }
});
Run Code Online (Sandbox Code Playgroud)