【问题标题】:jquery beforeunload when closing (not leaving) the page?jquery beforeunload 关闭(不离开)页面时?
【发布时间】:2013-09-17 23:27:16
【问题描述】:

如何显示“您确定要离开该页面吗?”当用户实际尝试关闭页面时(单击浏览器窗口或选项卡上的 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?';
        });
       }
    }
  })
}

【问题讨论】:

  • 你不能。您无法以编程方式区分浏览器关闭或用户离开您的页面。
  • @Cris 发生了什么错误??
  • 您的消息包含一些指示 Ajax 操作正在运行的代码。我们需要考虑其中一些吗? (因为除了那个代码,你没有明确提到它)
  • 你无法判断一个窗口是否关闭或导航到另一个 URL,考虑当你使用多标签浏览器时,没有区别,但如果你使用哈希导航(例如 @ 987654322@),你可以管理它在导航时抛出 javascript

标签: javascript jquery


【解决方案1】:

您可以使用 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();

});

这个解决方案适用于所有浏览器,我已经测试过了。

【讨论】:

  • 这是一个不错的选择(您可能也应该注意onsubmit),但它不适用于浏览器的后退和前进按钮。我预计没有理想的解决方案。
  • 代码没问题。如果用户单击“离开此页面”弹出按钮,我想运行 logout() 函数。但是如何检测用户是否点击了“离开此页面”?
  • $(window).on('unload', function() 未在 Safari 中执行。
  • 如果浏览器因操作系统关闭而关闭,beforeunload 会触发吗?
  • 您不能再在 Chrome 或 Firefox 中提供自定义消息(因为他们想防止诈骗):developers.google.com/web/updates/2016/04/…
【解决方案2】:

在你的 Ajax 中尝试 javascript

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

参考link

示例 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/

【讨论】:

    【解决方案3】:

    信用应该在这里: how to detect if a link was clicked when window.onbeforeunload is triggered?

    基本上,该解决方案添加了一个侦听器来检测链接或窗口是否导致 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?');
    }
    

    【讨论】:

      【解决方案4】:

      正如这里https://stackoverflow.com/a/1632004/330867 所指出的,您可以通过“过滤”产生此页面退出的内容来实现它。

      正如 cmets 中提到的,这是另一个问题中代码的新版本,其中还包括您在问题中提出的 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 提供的消息之前。原因如下:How can I override the OnBeforeUnload dialog and replace it with my own?

      【讨论】:

      • 从 jQuery 开始,1.7 .live 已弃用。应该使用$(document).on('click', 'a', ...) 而不是它。 .on 通常是优于 old 函数的首选方式,因此对于 .bind,它将是 $('form').on('submit', ...)
      • 我很确定这个答案不再是跨浏览器。有人测试过吗?
      • 如前所述,我只复制/粘贴了代码。我将使用最新版本编辑答案
      • 谢谢,但很遗憾,当我关闭标签时,确认没有出现。
      • .. 和我犯的一个大错误(单击而不是 beforeunload 作为文档事件)。
      【解决方案5】:

      试试这个,通过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>
      

      【讨论】:

      • 让您的用户在每次点击您网站中的链接时都等待同步 AJAX 调用的响应并不是一个好主意。
      【解决方案6】:

      您可以尝试“onbeforeunload”事件。

      也看看这个-

      Dialog box runs for 1 sec and disappears?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-01
        • 1970-01-01
        • 2014-02-08
        • 2016-09-13
        • 1970-01-01
        • 1970-01-01
        • 2013-02-25
        • 2020-10-27
        相关资源
        最近更新 更多