Skip to content

Instantly share code, notes, and snippets.

@dcvogi
Last active December 11, 2017 09:36
Show Gist options
  • Save dcvogi/1497e9189ddca605c8b384bbfea4bbc1 to your computer and use it in GitHub Desktop.
Save dcvogi/1497e9189ddca605c8b384bbfea4bbc1 to your computer and use it in GitHub Desktop.
Tracks the battery on load and before unload
function collectBatteryUsage(stage){
navigator.getBattery().then(function(batteryManagerData){
ga('send', 'event', 'battery usage', stage, String(batteryManagerData.level));
});
}
(function trackBatteryUsage(){
if(!window.Promise){
ga('send', 'event', 'browser support features', 'Promises', 'unable to handle Promises');
return;
}
if(typeof(navigator.getBattery) !== 'function'){
ga('send', 'event', 'browser support features', 'Battery API', 'unable to handle Battery API');
return;
}
// Collect battery level when user enters the page.
collectBatteryUsage('initial');
// Collect battery level when user exits the page.
window.onbeforeunload(function(){
collectBatteryUsage('before exit');
return null;
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment