开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜