最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to determine if a user is actually looking at a web page? - Stack Overflow

programmeradmin6浏览0评论

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
Add a ment  | 

5 Answers 5

Reset to default 6

You 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.

发布评论

评论列表(0)

  1. 暂无评论