2014-09-13 21 views
0

我寫了下面的jquery,每3秒發送一次心跳回PHP,它工作正常。我這樣做的原因是要了解用戶當前登錄和使用該網站的內容。jquery查看頁面時發送心跳信息

setInterval(function() { 
    $.post('includes/heartbeat.php', {'heartBeatConfirmation': '1'}); 
},3000); 

漁獲我發現是它繼續心跳當用戶不看的部位 - 例如:他們仍然有瀏覽器打開,但在看其他網頁或者做一些事情。

有沒有辦法更新這個,所以只發送AJAX心跳,如果用戶使用該網站?

回答

1

您可以檢查窗口是否關注,如果關注,則只檢查心跳。 試試這個:

$(window).focus(function() { 
    heartbeat = setInterval(function() { 
    $.post('includes/heartbeat.php', {'heartBeatConfirmation': '1'}); 
    },3000); 
}) 
.blur(function() { 
    clearInterval(heartbeat); 
}); 

$(window).focus(); 
+0

這隻適用於'click'。 – loveNoHate 2014-09-13 05:39:10

+0

嘗試在末尾添加'$(window).focus();'來初始化它。 – 2014-09-13 05:41:19

+0

沒關係。我只是修補這個:http://stackoverflow.com/questions/923299/how-can-i-detect-when-the-mouse-leaves-the-window。似乎不在JSFIDDLE中工作。 :/ – loveNoHate 2014-09-13 05:42:37

1
$(document).ready(function(){ 

     heartBeatInterval = null; 

     $(window).focus(function() { 
      if(heartBeatInterval == null){ 
      heartBeatInterval = setInterval(function() { 
             $.post('includes/heartbeat.php', 
             {'heartBeatConfirmation': '1'} 
            ); 
            console.log('We have the fouces of the active tab'); 
           },1000); 
      } 
     }); 

     $(window).blur(function() { 
      heartBeatInterval = null; 
      console.log('We have the lost the focus of the active tab'); 
     }); 

    }); 
1

這僅僅是一個品味的問題我想:

$(window) 
.on('mouseleave', function(){ 
    clearInterval(inside); 
}) 
.on('mouseenter', function(){ 
    inside = setInterval(function() { 
    $.post('includes/heartbeat.php', {'heartBeatConfirmation': '1'}) 
    }, 3000) 
}) 

JSFIDDLE(提醒:window是 「結果」 Frame)。