admin管理员组文章数量:1321037
Is it possible to determine whether a user is active on the current web page or, say, focused on a different tab or window?
It seems that if you switch tabs, any JavaScript set on a timeout/interval continues running. It would be nice to be able to 'pause' the events when the user is not on the page.
Would something like attaching a mouseover event to the body work, or would that be too resource-intensive?
Is it possible to determine whether a user is active on the current web page or, say, focused on a different tab or window?
It seems that if you switch tabs, any JavaScript set on a timeout/interval continues running. It would be nice to be able to 'pause' the events when the user is not on the page.
Would something like attaching a mouseover event to the body work, or would that be too resource-intensive?
Share Improve this question asked Feb 12, 2011 at 23:35 DisgruntledGoatDisgruntledGoat 72.6k70 gold badges212 silver badges291 bronze badges 1- Do you want to find out whether he is looking out of the window? ;) – Felix Kling Commented Feb 12, 2011 at 23:39
5 Answers
Reset to default 6You can place onfocus
/onblur
events on the window
.
There's wide support for those events on the window.
Example:
window.onfocus = function() {
document.body.innerHTML += "<br>I've gained focus.";
};
window.onblur = function() {
document.body.innerHTML += "<br>I've lost focus.";
};
span {color:blue}
<span>CLICK IN AND OUT OF THIS FRAME.
<br><br>(It has its own "window" object).</span>
<br><br>
Open Web Analytics (and perhaps some other tracking tools) has action tracking
You can also use the visibilityState of the document:
document.addEventListener("visibilitychange", function() {
if( document.visibilityState === 'visible' ) {
// Do your thing
}
});
There is a wide acceptance of this API.
You could keep an alive variable going using mousemove
events (assuming the user does not leave the mouse still on the page). When this variable (a timestamp likely) has not been updated in x seconds, you could say the page is not active and pause any script.
As long as you do not do a lot of processing in the body event handler you should be okay. It should just update the variable, and then have a script poll it at a certain interval to do the processing/checks (say every 1000ms).
Attach listeners to mousemove, keyup and scroll to the document.
I use this throttle/debounce function (which works without jQuery, even though it's a jQuery plugin if jQuery is present) to only run code in response to them once in ~250ms, so that you're not firing some code on every pixel of the mouse moving.
本文标签: javascriptHow to determine if a user is actually looking at a web pageStack Overflow
版权声明:本文标题:javascript - How to determine if a user is actually looking at a web page? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742095339a2420514.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论