当用户离开时触发事件 [英] Trigger an event when user navigates away
问题描述
当用户关闭窗口/标签或单击链接导航时,我需要在PHP页面上调用其中包含几行代码的JavaScript/jQuery函数.我已经尝试过onbeforeunload
函数,但是只有return "blah blah blah;"
部分会执行,其他所有内容都将被忽略.我还尝试了jQuery的.unload
方法,但由于某种原因该代码无法运行.
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.
$(window).unload(function() {
alert('blah blah blah');
});
请提出替代方案.谢谢.
Please suggest alternatives. Thanks..
推荐答案
这是一个简单的工作示例. unload
回调中的任何return
内容都将显示在浏览器弹出确认中.
Here is a simple working example. Whatever you return
from the unload
callback will be displayed in a browser popup confirmation.
工作示例,在卸载前发送Ajax请求 http://jsfiddle.net/alexflav23/hujQs/7/
最简单的方法:
window.onbeforeunload = function(event) {
// do stuff here
return "you have unsaved changes. Are you sure you want to navigate away?";
};
在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.
请记住,所有触发的操作都必须是同步的,因此您只能例如发出同步ajax请求.但是,以上内容在任何目的上都不是完全可靠的.
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.
选择将用户数据定期备份到localStorage
并自动与服务器同步.保留window.onbeforeunload
只是一种额外的预防措施,而不是主要机制.引起问题是众所周知的.
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.
这篇关于当用户离开时触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!