-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbrowsertab.js
287 lines (244 loc) · 8.78 KB
/
browsertab.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
;(function(){
/*
BrowserTab
Helper object for tracking whether a browser tab is "primary" and/or "hidden".
* `options.window` window object (defaults to global window)
* `options.document` document object (defaults to global document)
* `options.localStorage` localStorage to use (defaults to global localStorage)
* `options.storageNamespace` namespace for localStorage to coordinate "primary" tabs (defaults to "_BrowserTabStorageNamespace")
*/
function BrowserTab(options) {
var self = this;
options = options || {};
this._win = options.window || window;
this._doc = options.document || this._win.document;
this._prefixes = ["webkit", "moz", "ms", "o"];
// Only allow one tab to be "primary" per domain.
this._localStorage = options.localStorage || this._win.localStorage;
this._storageNamespace = options.storageNamespace || "_BrowserTabStorageNamespace";
this._id = ("" + Math.random() + Math.random()).replace(/\./g, "");
function release() {
self._releasePrimary();
}
this._listen(this._win, "unload", release);
this._listen(this._win, "beforeunload", release);
// Use the Visibility API if available, otherwise fallback to focus/blur.
// http://www.nczonline.net/blog/2011/08/09/introduction-to-the-page-visibility-api/
if (this._supportsVisibility()) {
this._initializeWithVisibility();
} else {
this._initializeWithBlurring();
}
// Initialize primary state.
if (!this.hidden() || !this._anyTabsPrimary()) {
this._makePrimary();
}
}
;(function(p){
// Expose class-level primary/hidden attributes for the common case.
var globalInstance;
BrowserTab.primary = function primary() {
globalInstance = globalInstance || new BrowserTab();
return globalInstance.primary();
};
BrowserTab.hidden = function hidden() {
globalInstance = globalInstance || new BrowserTab();
return globalInstance.hidden();
};
BrowserTab.on = function on() {
globalInstance = globalInstance || new BrowserTab();
return globalInstance.on.apply(globalInstance, arguments);
};
// Returns true when this is the most-recently-used tab.
p.primary = function() {
if (arguments.length > 0) {
throw new Error("'primary' property is not settable");
}
if (!this._localStorage) {
if (window.console && window.console.warn) {
window.console.warn("localStorage is required to use the primary() property");
}
}
return this._localStorage.getItem(this._storageNamespace) === this._id;
};
// Returns true when this tab is hidden from view.
p.hidden = function() {
if (arguments.length > 0) {
throw new Error("'hidden' property is not settable");
}
if (this._supportsVisibility()) {
return this._getProperty(this._doc, "hidden");
} else {
return this._blurred;
}
};
// Listens for changes to the hidden and primary attributes.
p.on = function(events, callback) {
events = events.split(/\s+/);
for (var i=0; i < events.length; i++) {
var event = events[i];
switch (event) {
case "change:hidden":
this._listenForVisibilityChange(callback);
break;
case "change:primary":
this._listenForPrimaryChange(callback);
break;
default:
throw new Error("invalid event '" + event + "'");
}
}
};
// Define private helpers.
p._getProperty = function(obj, name) {
var prefixableName = name.charAt(0).toString().toUpperCase() + name.slice(1);
if (name in obj) {
return obj[name];
} else {
var value;
this._eachBrowserPrefix(function(prefix) {
var prefixedName = prefix + prefixableName;
if (prefixedName in obj) {
value = obj[prefixedName];
}
});
return value;
}
};
p._supportsVisibility = function() {
var visibilityState = this._getProperty(this._doc, "visibilityState");
return visibilityState !== "undefined";
};
p._eachBrowserPrefix = function(callback) {
for (var i=0; i < this._prefixes.length; i++) {
callback(this._prefixes[i]);
}
};
p._listen = function(el, ev, fn) {
// http://javascriptrules.com/2009/07/22/cross-browser-event-listener-with-design-patterns/
// http://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript
if (el.addEventListener) {
el.addEventListener(ev, fn, false);
} else if (el.attachEvent) {
el.attachEvent('on' + ev, fn);
} else {
el['on' + ev] = fn;
}
};
p._listenForVisibilityChange = function(callback) {
var self = this;
this._listen(this._doc, "visibilitychange", callback);
this._eachBrowserPrefix(function(prefix) {
self._listen(self._doc, prefix + "visibilitychange", callback);
});
// If we are using blur changes, use that callback list instead.
if (this._blurChangeCallbacks) {
this._blurChangeCallbacks.push(callback);
}
};
p._listenForPrimaryChange = function(callback) {
var self = this;
if (this._localStorage) {
// http://html5doctor.com/storing-data-the-simple-html5-way-and-a-few-tricks-you-might-not-have-known/
this._listen(this._win, "storage", function(event) {
event = event || window.event;
if (event.key === self._storageNamespace) {
callback();
}
});
}
};
p._makePrimary = function() {
if (this._localStorage) {
this._localStorage.setItem(this._storageNamespace, this._id);
}
};
p._releasePrimary = function() {
if (this._localStorage) {
var primaryTabID = this._localStorage.getItem(this._storageNamespace);
if (primaryTabID === this._id) {
this._localStorage.removeItem(this._storageNamespace);
}
}
};
p._anyTabsPrimary = function() {
if (this._localStorage) {
var primaryTabID = this._localStorage.getItem(this._storageNamespace);
return primaryTabID !== "undefined";
// When no localStorage available, fail open.
} else {
return false;
}
};
p._initializeWithVisibility = function() {
var self = this;
this._blurred = this.hidden();
this._uncertain = false;
function syncPrimary() {
self._blurred = self.hidden();
if (!self.hidden()) {
self._makePrimary();
}
}
syncPrimary();
this._listenForVisibilityChange(syncPrimary);
};
p._initializeWithBlurring = function() {
// The main limitation with this fallback is that onblur is never called
// when switching tabs (only when switching windows).
var self = this;
this._blurred = false;
this._uncertain = true;
this._blurChangeCallbacks = [];
var blurChangeCallbacks = this._blurChangeCallbacks;
function triggerBlurChangeCallbacks() {
for (var i=0; i < blurChangeCallbacks.length; i++) {
setTimeout(blurChangeCallbacks[i], 0);
}
}
function blur() {
self._blurred = true;
self._uncertain = false;
triggerBlurChangeCallbacks();
}
function focus() {
self._blurred = false;
self._uncertain = false;
self._makePrimary();
triggerBlurChangeCallbacks();
}
// IE9 and lower have focusin/out on document.
this._listen(this._doc, "focusin", focus);
this._listen(this._doc, "focusout", blur);
// All other browsers have focus/blur on window.
this._listen(this._win, "focus", focus);
this._listen(this._win, "blur", blur);
// Since focus may not always trigger (e.g. when switching tabs),
// we also use other actions to consider this tab focused.
this._listen(this._doc, "scroll", focus);
this._listen(this._doc, "keydown", focus);
this._listen(this._doc, "mousemove", focus);
this._listen(this._doc, "select", focus);
this._listen(this._win, "scroll", focus);
this._listen(this._win, "keydown", focus);
this._listen(this._win, "mousemove", focus);
this._listen(this._win, "select", focus);
// When this becomes non-primary, it also must be blurred.
this._listenForPrimaryChange(function() {
if (!self.primary()) {
blur();
}
});
};
})(BrowserTab.prototype);
// Export for CommonJS.
if (typeof module !== "undefined") {
module.exports = BrowserTab;
// Export for AMD loaders.
} else if (this.define && this.define.amd) {
this.define(function(){return BrowserTab});
// For vanilla browser includes.
} else {
this.BrowserTab = BrowserTab;
}
}).call(this);