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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18783535/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:31:15  来源:igfitidea点击:

jquery beforeunload when closing (not leaving) the page?

javascriptjquery

提问by Cris

How can I display "Are you sure you want to leave the page?" when the user actually tries to close the page (click the X button on the browser window or tab) not when he tries to navigate away from the page (click on another link).

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

My client wants a message to appear when the user tries to close the page "Are you sure you want to leave the page? You still have items in your shopping cart."

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

Unfortunately $(window).bind('beforeunload')doesn't fire only when the user closes the page.

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

jQuery:

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?';
        });
       }
    }
  })
}

回答by Human Being

You can do this by using JQuery.

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

For example,

对于例如

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

Your JQuerywill be,

你的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');
}

And to get the Leave message alertwill be,

要获得离开消息警报将是,

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

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

         logout();

});

This solution works in all browsers and I have tested it.

此解决方案适用于所有浏览器,我已经对其进行了测试。

回答by Nathan Srivi

Try javascript into your Ajax

在 Ajax 中尝试使用 javascript

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

Reference link

参考链接

Example 2:

示例 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.';
    }
};

Here it will alert the user every time he leaves the page, until he clicks on the button.

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

DEMO: http://jsfiddle.net/DerekL/GSWbB/show/

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

回答by Andy Merhaut

Credit should go here: how to detect if a link was clicked when window.onbeforeunload is triggered?

信用应该在这里: 如何检测当 window.onbeforeunload 被触发时是否点击了链接?

Basically, the solution adds a listener to detect if a link or window caused the unload event to fire.

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

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?');
}

回答by Cyril N.

As indicated here https://stackoverflow.com/a/1632004/330867, you can implement it by "filtering" what is originating the exit of this page.

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

As mentionned in the comments, here's a new versionof the code in the other question, which also include the ajax request you make in your question :

正如评论中提到的,这是另一个问题中代码的新版本,其中还包括您在问题中提出的 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?";
});

Important: You shouldn't have a global variable defined (here canExit), this is here for simpler version.

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

Note that you can't override completely the confirm message (at least in chrome). The message you return will only be prepended to the one given by Chrome. Here's the reason : How can I override the OnBeforeUnload dialog and replace it with my own?

请注意,您不能完全覆盖确认消息(至少在 chrome 中)。您返回的消息只会添加到 Chrome 提供的消息之前。原因如下:如何覆盖 OnBeforeUnload 对话框并将其替换为我自己的对话框?

回答by raduns

Try this, loading data via ajaxand displaying through return statement.

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

回答by halkujabra

You can try 'onbeforeunload' event.

您可以尝试 ' onbeforeunload' 事件。

Also take a look at this-

也看看这个——

Dialog box runs for 1 sec and disappears?

对话框运行 1 秒后消失?