Niraj Chauhan

Niraj Chauhan

#father#husband#SoftwareCraftsman#foodie#gamer#onepiece#naruto

Get your website visitors device battery status

Recently I added a functionality in one my clients website to notify user about battery status if they are running low on it.

The easiest way to do it is using navigator api.

So to get user’s device battery status, just use the code below:

if (navigator.getBattery) {
    // Chrome and latest firefox
    navigator.getBattery().then(function(battery) {
       console.log(battery);
    });
} else if (navigator.battery) {
    // Old Firefox. Deprecated - https://developer.mozilla.org/en-US/docs/Web/API/Navigator/battery
    console.log(battery);
} else {
    console.log("Your browser doesnt supports battery API");
}

Output:

Objects:
	charging:true
	dischargingTime:Infinity
	level:1

Methods:
	onchargingchange
	onchargingtimechange
	ondischargingtimechange
	onlevelchange
javascriptbattery