简体   繁体   English

AJAX 和用户离开页面

[英]AJAX and user leaving a page

I'm working on a chat and I'm trying to figure out how I can detect that the user has left the page or not.我正在聊天,我试图弄清楚如何检测到用户是否离开了页面。 Almost everything is being handled by the database to avoid the front end from messing up.几乎所有事情都由数据库处理,以避免前端混乱。

So what I'm trying to do is once the page is left for any reason (window closed, going to another page, clicking a link, etc.) an ajax call will be fired before a person leaves so I can update the database.所以我想做的是一旦页面因任何原因离开(窗口关闭、转到另一个页面、单击链接等),ajax 调用将在一个人离开之前被触发,以便我可以更新数据库。

This is what I've tried:这是我尝试过的:

$(window).unload(function(){
      $.post("script.php",{key_leave:"289583002"});
});

For some odd reason, it wouldn't work, and I've checked the php code, and it works fine.出于某种奇怪的原因,它不起作用,我检查了 php 代码,它工作正常。 Any suggestions?有什么建议么?

Try this: 尝试这个:

$(window).unload(function(){
    $.ajax({
        type: 'POST',
        url: 'script.php',
        async:false,
        data: {key_leave:"289583002"}
    });
});

Note the async:false , that way the browser waits for the request to finish. 请注意async:false ,浏览器会等待请求完成。

Using $.post is asynchronous, so the request may not be quick enough before the browser stops executing the script. 使用$.post是异步的,因此在浏览器停止执行脚本之前,请求可能不够快。

This isn't the correct way of doing this... Suppose the OS just hangs or something happens in the browsers process then this event wont be fired. 这不是正确的方法...假设操作系统只是挂起或在浏览器进程中发生了某些事情,那么此事件将不会被触发。 And you will never ever know when the user has left, showing him/her online ever after he/she has disconnected. 而且,您永远不会知道用户何时离开,在他/她断开连接之后显示他/她的在线状态。 Instead of this, what you can do is. 而不是这个,你可以做的是。

  1. Try connecting a socket so that you can know the user is disconnected when the socket is disconnected 尝试连接套接字,以便在断开套接字时可以知道用户已断开连接
  2. You can send a request to the server (say after every 1 sec) so that you can know that the user is still connected. 您可以向服务器发送请求(例如每1秒后发送一次),以便您可以知道用户仍处于连接状态。 If you didn't receive the request - even after 2 secconds - disconnect the user. 如果您没有收到请求 - 即使在2秒后 - 断开用户连接。

Try to add popup (prompt("leaving so early?")) after $.post. 尝试在$ .post之后添加弹出窗口(提示(“离开这么早?”))。 It may work. 它可能会奏效。 Tho it may be bad user experience. 这可能是糟糕的用户体验。 :) :)

The unload event is not recommended to detect users leaving the page.不建议使用unload事件来检测用户离开页面。 From MDN :来自MDN

Developers should avoid using the unload event... Especially on mobile, the unload event is not reliably fired.开发人员应避免使用 unload 事件……尤其是在移动设备上,unload 事件不会被可靠地触发。

Instead, use the visibilitychange event on document and/or the pagehide event on window (see links for details).相反,请使用document上的visibilitychange事件和/或window上的pagehide事件(有关详细信息,请参阅链接)。 For example:例如:

document.addEventListener('visibilitychange', function() {
    if (document.visibilityState === 'hidden') {
        $.ajax({
            type: 'POST',
            url: 'script.php',
            async:false,
            data: {key_leave: "289583002"}
        });
    }
});

Better yet, use Navigator.sendBeacon , which is specifically designed for the purpose of sending a small amount of analytics data to a server:更好的是,使用Navigator.sendBeacon ,它是专门为向服务器发送少量分析数据而设计的:

document.addEventListener('visibilitychange', function() {
    if (document.visibilityState === 'hidden') {
         navigator.sendBeacon('script.php', {key_leave: "289583002"});
    }
});

This is related to the answer above. 这与上面的答案有关。 https://stackoverflow.com/a/10272651/1306144 https://stackoverflow.com/a/10272651/1306144

This will execute the ajax call every 1 sec. 这将每1秒执行一次ajax调用。 (1000) (1000)

function callEveryOneSec() {
    $jx.ajax({}); // your ajax call
}

setInterval(callEveryOneSec, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM