If you, for whatever reason, would like to get information about a user’s battery life, you can luckily use JavaScript and navigator.getBattery to guide your way.

I’ve personally used this API in the past as just one consideration in determining whether to autoplay a background video on a site or not, and usually in combination with some basic device detection as well, for getting the best results for performance and battery life. I’m sure there a ton of other use cases out there for this though!

if (navigator.getBattery) {

	var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery;

	navigator.getBattery().then( function(battery) {
		// Outputs current battery level
		console.log('Current battery level is: ', battery.level);

		// If current battery level is above 50%...
		if (battery.level > 0.5) {
			console.log('Current battery level is over 50%!');

For more information, check out David Walsh’s article, JavaScript Battery API.

Leave a Reply

Your email address will not be published. Required fields are marked *

Continue Reading