jQuery 在没有对话框的情况下使用 onbeforeunload ?

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

Using onbeforeunload without dialog?

javascriptjqueryonbeforeunload

提问by user198989

I'm trying to post data when a user leaves my page. I have finally managed to find a working solution, however, it shows a confirmation dialog when the user leaves. I have tried return null;but it didn't work. Is it possible to disable the dialog?

当用户离开我的页面时,我试图发布数据。我终于找到了一个可行的解决方案,但是,当用户离开时,它会显示一个确认对话框。我试过了,return null;但没有用。是否可以禁用对话框?

window.onbeforeunload = function() {
    $.post("track.php", {
        async: false,
        refid: refid,
        country: country, 
        type: type,
    });

    return '';
}

回答by meesern

From the Mozilla Developer Network page:

Mozilla 开发者网络页面

When this event returns a non-void value, the user is prompted to confirm the page unload.

当此事件返回非空值时,系统会提示用户确认页面卸载。

This means the return value of the handler must be undefined(not '', false, or null) in order to avoid triggering the confirmation prompt.

这意味着处理程序的返回值必须是undefined(not '', false, or null) 以避免触发确认提示。

window.onbeforeunload = function() {

  $.post("track.php", {
  ...
  });

  return undefined;
}

In javascript you can skip the return value altogether to get the same result.

在 javascript 中,您可以完全跳过返回值以获得相同的结果。

In coffeescript with jquery it's something like

在带有 jquery 的咖啡脚本中,它类似于

$(document).ready ->
  $(window).bind('beforeunload', ->
    #put your cleanup code here
    undefined
  )

回答by Hay Thi

If you want to disable the dialog, please only write

如果你想禁用对话框,请只写

window.onbeforeunload = function() { ... return; }

window.onbeforeunload = function() { ... return; }

instead of

代替

window.onbeforeunload = function() { ... return ''; }.

window.onbeforeunload = function() { ... return ''; }.

I hope it will help you.

我希望它会帮助你。

回答by A. Wolff

Could you test this:

你能测试一下吗:

$(window).on('beforeunload', function (e) {
    if (e.originalEvent) $.post("track.php", {
        async: false,
        refid: refid,
        country: country,
        type: type,
    });
    else $.get("", {
        async: false
    });
    $(this).trigger('beforeunload');
}

This will create many useless requests but should let your first request enough time to reach server.

这将创建许多无用的请求,但应该让您的第一个请求有足够的时间到达服务器。

回答by mEnE

Removing returnstatement worked for me also.

删除return声明也对我有用。

回答by user198989

I have found a really simple trick to get this working with using

我发现了一个非常简单的技巧来使用

$(window).bind('onbeforeunload', function () {

$.post("track.php", {
async: false,
refid: refid,
country: country, 
type: type,
});

});