jQuery 当用户离开时触发事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15925251/
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
Trigger an event when user navigates away
提问by CobaltBabyBear
I need to call a JavaScript/jQuery function which has a few lines of code in it, on a PHP page when the user closes his window/tab or navigates away by clicking a link. I've tried the onbeforeunload
function but only the return "blah blah blah;"
part executes and everything else is ignored. I've also tried the .unload
method from jQuery but for some reason this code doesn't run.
当用户关闭他的窗口/选项卡或通过单击链接导航离开时,我需要在 PHP 页面上调用一个包含几行代码的 JavaScript/jQuery 函数。我已经尝试过该onbeforeunload
功能,但只有return "blah blah blah;"
部分执行,其他所有内容都被忽略。我也尝试过.unload
jQuery的方法,但由于某种原因,这段代码没有运行。
$(window).unload(function() {
alert('blah blah blah');
});
Please suggest alternatives. Thanks..
请提出替代方案。谢谢..
采纳答案by flavian
Here is a simple working example. Whatever you return
from the unload
callback will be displayed in a browser popup confirmation.
这是一个简单的工作示例。无论您return
从unload
回调中获得什么,都将显示在浏览器弹出确认中。
Working example sending Ajax request before unloadhttp://jsfiddle.net/alexflav23/hujQs/7/
在卸载http://jsfiddle.net/alexflav23/hujQs/7/之前发送 Ajax 请求的工作示例
The easiest way to do this:
最简单的方法:
window.onbeforeunload = function(event) {
// do stuff here
return "you have unsaved changes. Are you sure you want to navigate away?";
};
in jQuery:
在 jQuery 中:
$(window).on("beforeunload", function() {
$.ajax("someURL", {
async: false,
data: "test",
success: function(event) {
console.log("Ajax request executed");
}
});
return "This is a jQuery version";
});
Look into the Network tab of the browser. You will see how the request is being sent as you wanted to do. Just send the appropriate data.
查看浏览器的网络选项卡。您将看到请求是如何按照您的意愿发送的。只需发送适当的数据。
Bear in mind all operations triggered must be synchronous, so you can only make synchronous ajax requests for instance. However, the above is not entirely reliable for any purpose.
请记住,所有触发的操作都必须是同步的,因此您只能进行同步 ajax 请求。但是,上述内容对于任何目的都不是完全可靠的。
Opt for periodic back-up of user data to localStorage
and sync with the server automatically . Keep window.onbeforeunload
just as an extra precaution, but not as a main mechanism. It's well known to cause problems.
选择定期将用户数据备份到localStorage
服务器并自动与服务器同步。保留window.onbeforeunload
只是作为额外的预防措施,而不是作为主要机制。众所周知会引起问题。
回答by rococo
This is an old question, but I wanted to share an alternative approach that has the benefit of working with high consistency:
这是一个老问题,但我想分享一种具有高一致性的替代方法:
Establish a WebSocket connection to the server, and when the client navigates away the WebSocket connection will be closed. Server-side, you can detect the closed connection in a callback and run whatever code you need on the server.
建立到服务器的 WebSocket 连接,当客户端导航离开时,WebSocket 连接将关闭。服务器端,您可以在回调中检测关闭的连接并在服务器上运行您需要的任何代码。
Executing Javascript on page unload is often unreliable (as discussed in the other answer) because it's inherently at odds with the user's intention. This method will always work, although it is admittedly quite a bit more cumbersome to implement.
在页面卸载时执行 Javascript 通常不可靠(如另一个答案中所述),因为它本质上与用户的意图不一致。这种方法将始终有效,尽管实施起来确实有点麻烦。
This does change the context of your "run before leaving" code from client-side to server-side, but I imagine for most cases the difference is inconsequential. Anything you want to run client-side before the client leaves your page is probably not going to change anything the client sees, so it's probably fine to run it server side. If there is specific data you need from the client you can send it through the WebSocket to the server.
这确实将您的“离开前运行”代码的上下文从客户端更改为服务器端,但我认为在大多数情况下,差异是无关紧要的。在客户端离开您的页面之前,您想在客户端运行的任何内容可能都不会改变客户端看到的任何内容,因此在服务器端运行它可能没问题。如果您需要来自客户端的特定数据,您可以通过 WebSocket 将其发送到服务器。
The only situation I can think of off the top of my head where this might cause unexpected behavior is if the user loses the WS connection without actually navigating away, e.g. they lose internet or put their computer to sleep. Whether or not that's a big deal is probably highly dependent on what kind of code you're trying to execute.
我能想到的唯一可能会导致意外行为的情况是,如果用户在没有实际导航的情况下失去了 WS 连接,例如他们失去互联网或让他们的计算机进入睡眠状态。这是否是一个大问题可能在很大程度上取决于您尝试执行的代码类型。
回答by Jonas Lundman
In many projects of mine, the mentioned methods here are instable. The only thing that worksfor me is to bind the event as original attribute on the body element.
在我的很多项目中,这里提到的方法是不稳定的。那唯一的工作对我来说是绑定事件为主体元素的原始属性。
<body onunload="my_function_unload()">
jQuery method:
jQuery方法:
$('body').attr('onunload', 'my_function_unload()');
From an iframe:
从 iframe:
<body onunload="window.parent.my_function_unload()">
jQuery method:
jQuery方法:
$('<iframe />').load(function(){
$body = $(this).contents().find('body');
$body.attr('onunload', 'window.parent.my_function_unload()');
}
Also, important, no arguments in the attribute, and the function must be in the global window scope, otherwise nothing happens.
另外,important,属性中没有参数,并且函数必须在全局窗口范围内,否则什么都不会发生。
For example, common mistake If your my_function_unload()
are wrapped inside a ;( function( $ ) {...
OR $(document).ready(function(){...
AS my_function_unload()
must be outside that private scope. And dont forget to use jQuery
instead of $
prefix then. (Working with Wordpress for example)
例如,常见错误如果您my_function_unload()
被包裹在;( function( $ ) {...
OR 内,则$(document).ready(function(){...
ASmy_function_unload()
必须在该私有范围之外。并且不要忘记使用jQuery
而不是$
前缀。(例如使用 Wordpress)