Skip to content

Instantly share code, notes, and snippets.

@defims
Forked from Kambfhase/LICENSE.txt
Last active June 14, 2016 01:31
Show Gist options
  • Save defims/5de3181ce514baa639b6b22f5f099cdf to your computer and use it in GitHub Desktop.
Save defims/5de3181ce514baa639b6b22f5f099cdf to your computer and use it in GitHub Desktop.
activity detection

I've been hanging around in the jQuery IRC-Channel today, when somebody came in and asked a simple question:

<simulation> how can i know if the page is on visible tab or passive tab ?

At first I thought this'd be impossible. Neither I there an API that I know of, nor should it be possible because of privacy. (Note: There are Fx internal APIs like tabs.focused)

Thankfully recently Browser vendors added the requestAnimationFrame function. We can use that to hack something together.

load the reqAF-shim: https://gist.github.com/997619 and save it to any variable, eg reqAF.

function( c, r){
// c: the callback
// r: the requestAnimationFrame function
setTimeout(function(){
// if c is still defined, call it with the
// param false and set c to false
c&&c(c=!1)
},50);
r(function(){
// if c is still defined, call it with the
// param true and set c to 0( falsy)
c&&c(!(c=0))
})
}
export function(c,r){setTimeout(function(){c&&c(c=!1)},50);r(function(){c&&c(!(c=0))})}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Kambfhase
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "activity detection",
"description": "detects if the user is looking at your page right now.",
"keywords": [ "five", "descriptive", "keywords", "or", "fewer" ],
"version": "0.1.0"
}
<!DOCTYPE html>
<title>detect activity</title>
<script>
var reqAF= function(a,b){while(a--&&!(b=this["oR0msR0mozR0webkitR0r".split(0)[a]+"equestAnimationFrame"]));return b||function(a){setTimeout(a,15)}}(5);
var active = function(c,r){setTimeout(function(){c&&c(c=!1)},50);r(function(){c&&c(!(c=0))})};
function checkLater(){
setTimeout( function(){
active(function( a){
console.log( a);
}, reqAF);
}, 1000);
}
</script>
<a href="javascript: checkLater();">Check if this page is active. when in doubt, logs true.</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment