正在阻止用户使用“window.oneforeunload”导航离开



当用户单击后退前进刷新浏览器按钮时,我试图显示警报,但我没有得到所需的输出。。。

<script type="text/javascript">
    $(document).ready(displayAlert());
    function displayAlert() {
        window.onbeforeunload = function () {
            return "Are you sure want to LOGOUT the session ?";
        };
    }       
</script>

WindowEventHandlers.onunload当窗口卸载其内容和资源时,会引发卸载事件。资源删除是在卸载事件发生后处理的。

window.onunload = funcRef;

WindowEventHandlers.onbeforeunload当窗口即将卸载其资源时激发的事件。文档仍然可见,事件仍然可以取消。

window.onbeforeunload = function(e) {
  return 'Dialog text here.';
};

IE与onload事件有问题,Opera与onbeforeunload有问题。因此,为了找到一个能够处理这两种情况的解决方案,我遇到了user3253009答案

/*Code Start*/
var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
    var confirmationMessage = 'Cookies for you.. If you stay back!!?'; // a space
    (e || window.event).returnValue = confirmationMessage;
    return confirmationMessage;
});
/*Code End*/

Gist。希望它能有所帮助!

更新

如果您想在用户离开您的页面时显示引导模式,那么您可以尝试以下操作:

window.onbeforeunload = function(event) {
    event.preventDefault();
    $('#cancel_modal').modal('show');
};

最新更新