Created
March 4, 2014 22:52
-
-
Save sym3tri/9357439 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | |
} | |
}); |
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
Thanks, for those not using underscore/lodash, here is the
isBoolean
source from http://underscorejs.org/docs/underscore.html