-
Notifications
You must be signed in to change notification settings - Fork 4
/
jquery.pagevisibility.js
91 lines (78 loc) · 3.04 KB
/
jquery.pagevisibility.js
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*! jquery.pagevisibility v0.2.2 | (c) 2013 Daniel Herman | opensource.org/licenses/MIT */
(function (factory) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
"use strict";
var prefix, prefixes, polyfillHidden, visibilityState, supportsVisibilityApi, hiddenProperty, defineProp, document;
document = window.document;
defineProp = Object.defineProperty || $.noop;
supportsVisibilityApi = false;
prefixes = [ "ms", "moz", "webkit", "" ];
while( prefixes.length ) {
prefix = prefixes.pop();
hiddenProperty = prefix ? prefix + "Hidden" : "hidden";
if ( hiddenProperty in document ) {
supportsVisibilityApi = true;
break;
}
}
if ( !supportsVisibilityApi ) {
// Add a good enough unprefixed polyfill for browsers that don't support the visibility API
// and set the initial values.
polyfillHidden = document.hidden = false;
visibilityState = document.visibilityState = "visible";
// Support: Android < 4
// http://bugs.jquery.com/ticket/13494
// http://caniuse.com/#feat=pagevisibility
try {
defineProp( document, "hidden", {
get: function() {
return polyfillHidden;
},
set: $.noop
});
defineProp( document, "visibilityState", {
get: function() {
return visibilityState;
},
set: $.noop
});
}
catch ( e ) {}
$( window ).bind( "focus blur", function( e ) {
var shouldBeHidden = e.type === "blur";
if ( polyfillHidden !== shouldBeHidden ) {
// In browsers that support Object.defineProperty,
// setting the two properties on document is essentially a no-op.
// In other older browsers, this is how we'll keep the properties in sync,
// although it's more prone to tampering than with Object.defineProperty.
document.hidden = polyfillHidden = shouldBeHidden;
document.visibilityState = visibilityState = shouldBeHidden ? "hidden" : "visible";
$( document ).trigger( "visibilitychange" );
}
});
}
else if ( prefix ) {
// If we're dealing with a prefixed version of the API, then
// normalize it so that we can use the same API across browsers.
$.event.special.visibilitychange = {
bindType: prefix + "visibilitychange"
};
defineProp( document, "hidden", {
get: function() {
return document[ hiddenProperty ];
}
});
defineProp( document, "visibilityState", {
get: function() {
return document[ prefix + "VisibilityState" ];
}
});
}
}));