关闭(不离开)页面时的jQuery beforeunload?


83

如何显示“您确定要离开页面吗?” 当用户实际上试图关闭页面(单击浏览器窗口或选项卡上的X按钮)时,而不是当用户试图离开页面导航(单击另一个链接)时。

我的客户希望用户尝试关闭页面时显示一条消息“您确定要离开页面吗?您的购物车中仍然有商品。”

不幸的是$(window).bind('beforeunload'),仅当用户关闭页面时才会触发。

jQuery的:

function checkCart() { 
  $.ajax({
    url : 'index.php?route=module/cart/check',
    type : 'POST',
    dataType : 'json',
    success : function (result) {
       if (result) {
        $(window).bind('beforeunload', function(){
          return 'leave?';
        });
       }
    }
  })
}


1
你不能 您无法以编程方式判断浏览器关闭或用户离开页面导航之间的区别。
meagar

@Cris发生了什么错误?
Padmanathan J

您的消息中包含一些代码,这些代码指示Ajax操作正在运行。我们需要考虑其中一些吗?(因为除了该代码外,您没有明确提及它)
Cyril N.

您无法判断是关闭窗口还是导航到另一个URL,请考虑使用多标签浏览器时没有什么区别,但是如果使用哈希导航(例如yourdomain.com/#path=/index / news&id = 1),您可以管理在浏览时抛出javascript
alphakevin 2013年

Answers:


145

您可以使用JQuery做到这一点。

对于例如

<a href="your URL" id="navigate"> click here </a>

JQuery会的

$(document).ready(function(){

    $('a').on('mousedown', stopNavigate);

    $('a').on('mouseleave', function () {
           $(window).on('beforeunload', function(){
                  return 'Are you sure you want to leave?';
           });
    });
});

function stopNavigate(){    
    $(window).off('beforeunload');
}

而要获得“离开消息”警报

$(window).on('beforeunload', function(){
      return 'Are you sure you want to leave?';
});

$(window).on('unload', function(){

         logout();

});

该解决方案适用于所有浏览器,并且已经过测试。


2
这是一个不错的选择(您可能也应该注意onsubmit),但不适用于浏览器的“后退”和“前进”按钮。我预计没有理想的解决方案。
noseratio

代码很好。如果用户单击“离开此页面”弹出按钮,我想运行logout()函数。但是,如何检测用户是否单击了“离开此页面”?
Bit_hunter

1
$(window).on('unload', function()在Safari中未执行此操作。
Aarohi Kulkarni 2015年

1
beforeunload如果浏览器由于操作系统关闭而关闭,是否会触发?
techie_28 '16

4
:在Chrome或Firefox不能提供自定义的消息了(因为他们要防止诈骗)developers.google.com/web/updates/2016/04/...
亚当

12

在您的Ajax中尝试使用javascript

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

参考链接

范例2:

document.getElementsByClassName('eStore_buy_now_button')[0].onclick = function(){
    window.btn_clicked = true;
};
window.onbeforeunload = function(){
    if(!window.btn_clicked){
        return 'You must click "Buy Now" to make payment and finish your order. If you leave now your order will be canceled.';
    }
};

在这里,它会在用户每次离开页面时提醒用户,直到他单击按钮。

演示:http : //jsfiddle.net/DerekL/GSWbB/show/


12

功劳应该放在这里: 触发window.onbeforeunload时,如何检测链接是否被单击?

基本上,该解决方案添加了一个侦听器,以检测链接或窗口是否导致触发了unload事件。

var link_was_clicked = false;
document.addEventListener("click", function(e) {
   if (e.target.nodeName.toLowerCase() === 'a') {
      link_was_clicked = true;
   }
}, true);

window.onbeforeunload = function(e) {
    if(link_was_clicked) {
        return;
    }
    return confirm('Are you sure?');
}

2

如此处https://stackoverflow.com/a/1632004/330867所示,您可以通过“过滤”导致此页面退出的内容来实现它。

如评论中所述,这是另一个问题中代码的新版本,其中还包括您在问题中提出的ajax请求:

var canExit = true;

// For every function that will call an ajax query, you need to set the var "canExit" to false, then set it to false once the ajax is finished.

function checkCart() {
  canExit = false;
  $.ajax({
    url : 'index.php?route=module/cart/check',
    type : 'POST',
    dataType : 'json',
    success : function (result) {
       if (result) {
        canExit = true;
       }
    }
  })
}

$(document).on('click', 'a', function() {canExit = true;}); // can exit if it's a link
$(window).on('beforeunload', function() {
    if (canExit) return null; // null will allow exit without a question
    // Else, just return the message you want to display
    return "Do you really want to close?";
});

重要提示:您不应该定义全局变量(在此canExit),此处用于更简单的版本。

请注意,您不能完全覆盖确认消息(至少在Chrome中是这样)。您返回的消息仅位于Chrome给出的消息之前。原因如下:如何覆盖OnBeforeUnload对话框并将其替换为我自己的对话框?


3
从jQuery开始1.7 .live不推荐使用。代替它,$(document).on('click', 'a', ...) 应该使用。.on通常是比函数更好的方式,.bind因为它将是$('form').on('submit', ...)
t.niese 2013年

我很确定这个答案不再是跨浏览器。有人测试过吗?
A. Wolff 2013年

如前所述,我只复制/粘贴了代码。我将编辑最新版本的答案
西里尔(Cyril N)

谢谢,但是不幸的是,当我关闭标签时,确认没有出现。
Cris 2013年

..和我犯的一个大错误(单击而不是beforeunload作为document事件)。
西里尔(Cyril N.)

-1

尝试此操作,通过加载数据ajax并通过return语句显示。

<script type="text/javascript">
function closeWindow(){

    var Data = $.ajax({
        type : "POST",
        url : "file.txt",  //loading a simple text file for sample.
        cache : false,
        global : false,
        async : false,
        success : function(data) {
            return data;
        }

    }).responseText;


    return "Are you sure you want to leave the page? You still have "+Data+" items in your shopping cart";
}

window.onbeforeunload = closeWindow;
</script>

1
让您的用户每次单击站点中的链接时都等待同步AJAX调用的响应不是一个好主意。
mattalxndr

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.