Skip to content

Instantly share code, notes, and snippets.

@sym3tri
Created March 4, 2014 22:52
Show Gist options
  • Save sym3tri/9357439 to your computer and use it in GitHub Desktop.
Save sym3tri/9357439 to your computer and use it in GitHub Desktop.
angular.module('myServices')
.factory('visibilityBroadcaster', function($rootScope, $document, _) {
var document = $document[0],
features,
detectedFeature;
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]);
}
});
@zachdunn
Copy link

For people looking to avoid extra watchers on unsupported browsers, returning the detectedFeature as a boolean makes the check easy: https://gist.github.com/zachdunn/de9f44bef5a39bf3b28f#file-visibility-broadcaster-js-L50-L52

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment