Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript detect user is viewing the page

Tags:

javascript

Currently my website keep auto reload a javascript function for every 10 seconds by setInterval( "checklatestmsgidLive();", 10000 ); I think the function will still keep reloading the function even when the user is viewing other website on other tab. How to make it reload the function only when the user is viewing my website? Can javascript detect if the user is viewing my website?

I saw facebook.com wall also update new posts only when I am viewing the page, when I am on other tab, it won't update the new posts. How to do that?

like image 837
zac1987 Avatar asked Jun 10 '11 14:06

zac1987


2 Answers

var tId, idleTimer;
function initReload() { 
  clearInterval(tId);
  tId = setInterval(checklatestmsgidLive, 10000 );

}
window.onload=window.onfocus=function() {
  initReload()
}
window.onblur=function() {
  clearInterval(tId);
}
window.onmousemove=function() {
  clearTimeout(idleTimer);
  idleTimer = setTimeout(function() { clearInterval(tId);},600000); // idle for 10 minutes
}
like image 158
mplungjan Avatar answered Sep 23 '22 07:09

mplungjan


Mouse move doesn't work very well on touch devices without a mouse, but we don't have a lot of options yet. W3C is working on a new API: Page Visibility. It's still in a very early stage, and the only browsers I could find that have started implementing it are Google Chrome (Dev Channel) and Internet Explorer 10 Platform Preview.

Since the spec is still a draft, the properties and events are vendor prefixed. But it still works, and Chrome has an extremely quick update rate. So I would try to detect if Page Visibility is available, and if not fallback to the mouse move hack.

The IE-team has a live demo that works in Chrome Dev and IE 10 platform preview.

like image 20
gregers Avatar answered Sep 23 '22 07:09

gregers