Posts Detect if browser tab is active
Post
Cancel

Detect if browser tab is active

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//source :
http://dystroy.org/demos/vis-en.html
http://stackoverflow.com/a/19519701

var vis = (function(){
	var stateKey, eventKey, keys = {
		hidden: "visibilitychange",
		webkitHidden: "webkitvisibilitychange",
		mozHidden: "mozvisibilitychange",
		msHidden: "msvisibilitychange"
	};
	for (stateKey in keys) {
		if (stateKey in document) {
			eventKey = keys[stateKey];
			break;
		}
	}
	return function(c) {
		if (c) {
			document.addEventListener(eventKey, c);
			//document.addEventListener("blur", c);
			//document.addEventListener("focus", c);
		}
		return !document[stateKey];
	}
})();

vis(function(){
	document.title = vis() ? 'Visible' : 'Not visible';
	console.log(new Date, 'visible ?', vis());
});

// to set the initial state
document.title = vis() ? 'Visible' : 'Not visible';

origin - http://www.pipiscrew.com/?p=5922 js-detect-if-browser-tab-is-active

This post is licensed under CC BY 4.0 by the author.
Contents

Trending Tags