Javascript 'beforeunload' Chrome 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10680544/
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
'beforeunload' Chrome Issue
提问by skos
I have this simple piece of code -
我有这段简单的代码 -
$(window).bind('beforeunload', function(){
alert("Good Bye")
});
Works great with Firefox, IE8 but not in Chrome. Is it a known problem or is there any alternative for that ?
适用于 Firefox、IE8,但不适用于 Chrome。这是一个已知问题还是有其他选择?
Actually what I am trying to do is to log details whenever user tries to close the browser.
实际上我想做的是在用户尝试关闭浏览器时记录详细信息。
function LogTime()
{
jQuery.ajax({
type: "POST",
url: "log.php",
data: "",
cache: false,
success: function(response)
{
}
);
}
$(window).bind('beforeunload', function(){
LogTime();
});
This works well in Firefox, but not in Chrome
这适用于 Firefox,但不适用于 Chrome
回答by Sampson
Return a string instead:
改为返回一个字符串:
$(window).on('beforeunload', function(){
return "Good bye";
});?
回答by xdazz
Try below:
试试下面:
$(window).on('beforeunload', function(){
return "Good Bye";
});
回答by Abhishek Salgaonkar
Try this for all Browsers:-
为所有浏览器尝试此操作:-
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
e.returnValue = confirmationMessage;
return confirmationMessage;
});
回答by user1703776
I had to include it in a jQuery(document).ready to get it working in chrome
我必须将它包含在 jQuery(document) 中。准备好让它在 chrome 中工作
<script>
jQuery(document).ready(
function () {
jQuery(window).bind('beforeunload',
function (e) {
[code here]
}
);
}
);
</script>
回答by Marcelo Noronha
Try this:
尝试这个:
function LogTime(){
jQuery.ajax({
type: "POST",
url: "log.php",
data: "",
cache: false,
success: function(response){
}
});
}
}
$(window).bind('beforeunload', function(){
LogTime();
return "You're leaving?";
});
It seems that as long as you return a string for this event at the end of function body, you can run code before that string.
似乎只要在函数体的末尾为此事件返回一个字符串,就可以在该字符串之前运行代码。
回答by miro
If you need to send some analytical data just before unloading the document, choose navigator.sendBeacon()method instead of XMLHttpRequest.
如果您需要在卸载文档之前发送一些分析数据,请选择navigator.sendBeacon()方法而不是 XMLHttpRequest。
sendBeacon() method is designed to perform non-blocking sending of a small amount of data.
sendBeacon() 方法旨在执行少量数据的非阻塞发送。
But check canIuse reportfirst, since the method is not supported globally yet.
但是首先检查canIuse 报告,因为该方法尚不受全球支持。