Skip to content

Instantly share code, notes, and snippets.

@zachdunn
Forked from sym3tri/visibility-broadcaster.js
Last active August 29, 2015 14:23
Show Gist options
  • Save zachdunn/de9f44bef5a39bf3b28f to your computer and use it in GitHub Desktop.
Save zachdunn/de9f44bef5a39bf3b28f to your computer and use it in GitHub Desktop.
(function () {
'use strict';
/**
* Broadcast changes to the page's visibility (via page visibility API)
* Source: https://gist.github.com/sym3tri/9357439
*/
function VisibilityService ($document, $rootScope, _) {
var document = $document[0],
features,
detectedFeature;
// Cross-browser implementation
features = {
standard: {
eventName: 'visibilitychange',
propertyName: 'hidden'
},
moz: {
eventName: 'mozvisibilitychange',
propertyName: 'mozHidden'
},
ms: {
eventName: 'msvisibilitychange',
propertyName: 'msHidden'
},
webkit: {
eventName: 'webkitvisibilitychange',
propertyName: 'webkitHidden'
}
};
Object.keys(features).some(function(feature) {
if (_.isBoolean(document[features[feature].propertyName])) {
detectedFeature = features[feature];
return true;
}
});
// Feature doesn't exist in browser.
if (!detectedFeature) {
return;
}
$document.on(detectedFeature.eventName, broadcastChangeEvent);
function broadcastChangeEvent () {
$rootScope.$broadcast('visibilityChange', document[detectedFeature.propertyName]);
}
return {
supported: !!detectedFeature
}
}
angular.module('myServices').service('visibilityService', ['$document', '$rootScope', '_', VisibilityService]);
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment