jQuery 单击浏览器后退按钮时如何调用事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25682671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call an event when browser back button is clicked
提问by Ankit Sahrawat
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.
单击浏览器后退按钮时如何调用 jquery 事件。我在 asp.net mvc 中使用单页应用程序,当用户按下浏览器的后退按钮时,我想显示一个确认框以离开屏幕。如何在浏览器后退按钮上调用 jquery 函数。请帮忙。我已经搜索并找到了推送状态事件,但我没有了解如何在上述情况下使用它。
采纳答案by Varun
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 ();
}
});
}
});
回答by Charles-Antoine Fournel
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.');
});
}
});