我的应用程序是MVC5,我想在用户关闭浏览器选项卡时提醒他们。 我找到了这个解决方案Setting onbeforeunload on body element in Chrome and IE using jQuery ,效果很好,除了我在少数情况下使用 location.href (Telerik 网格内的自定义命令按钮)。 尝试了以下方法:
$(window).bind('hashchange', function() {
validNavigation = true;
});
避免询问用户是否要离开页面。 有没有更好的方法在关闭浏览器选项卡之前提醒用户?
最佳答案
试试这个;)
需要对此代码进行一些修改:
window.onbeforeunload = function() {
if(validNavigation){
validNavigation = false;
/* if this click is valid means user action is not close window or reload page then just return; */
return;
}
/* Want to ask user before leaving the page */
return "Are you sure you want to leave this page bla bla bla?"; // you can make this dynamic, ofcourse...
};
validNavigation = true;
$(document).on('click', '.validNavigation', function(){
validNavigation = true;
});
现在您需要做的是将 validNavigation
类添加到您不想向用户显示 onbeforeunload
消息的所有链接;
更新根据评论:
function gotopage(args){
/* set validNavigation to true to don't show warning on page load; */
validNavigation = true;
window.location.href = [args];
}
对于您不想向用户显示警告的操作,只需设置 validNavigation = true;
并在其后面放置语句可能会导致位置更改;
关于javascript - onbeforeunload 使用 location.href 进行导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36687168/