开发者

How to determine if a user is actually looking at a web page?

开发者 https://www.devze.com 2023-02-09 23:40 出处:网络
Is it possible to determine whether a user is active on the current web page or, say, focused on a different ta开发者_如何学编程b or window?

Is it possible to determine whether a user is active on the current web page or, say, focused on a different ta开发者_如何学编程b 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?


You can place onfocus/onblur events on the window.

There's wide support for those events on the window.

Example: http://jsfiddle.net/xaTt4/

window.onfocus = function() {
    // do something when this window object gets focus.
};

window.onblur = function() {
    // do something when this window object loses focus.
};


Open Web Analytics (and perhaps some other tracking tools) has action tracking


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.


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.

0

精彩评论

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