简体   繁体   中英

javascript detect user is viewing the page

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?

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
}

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.

An easy solution would be to detect a mouse move in your page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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