DEV Community 👩‍💻👨‍💻

Cover image for How to check battery status with javascript ( 2 simple steps )
Anand Raj
Anand Raj

Posted on

How to check battery status with javascript ( 2 simple steps )

In this tutorial I am going to show you how easily you can check battery status of system using javascript battery API .

Using the battery API various information about the system battery can be extracted , thus increasing the user experience also , in case user needs urgent charging .

Getting battery Information

The battery API is not working in all browser , so first of all before getting the battery status we need to check that if browser supports the battery API or not .

Checking API working in browser

Now to check the working of API in browser we need to use getBattery method on navigator API , as shown in the example below .

if(navigator.getBattery){
    // if battery API is working
}
else{
    // if battery API is not working
}
Enter fullscreen mode Exit fullscreen mode

Check battery status

If the battery API is working then we can check the battery percentage with getBattery() API , this API returns a promise .

navigator.getBattery()
    .then(function(battery) {

        // Get current battery level .
        var batteryLevel = battery.level * 100;
        console.log(batteryLevel);
    })
    .catch(function(e) {
        console.error(e);
    });
Enter fullscreen mode Exit fullscreen mode

The battery object has the following properties we can use to extract more information about sytem battery .

  • battery.level : to check the battery level
  • battery.charging : to check if the battery is currently charging or not (true/false)
  • battery.chargingTime : to check the time remaining in full charge of battery
  • battery.dischargingTime : to check the time remaining in battery dead .

Now to detect changes in all these properties at real time javascript provide us some event listeners , as shown below .

  • battery.onlevelchange : to detect change in battery level
  • battery.onchargingchange : to detect change in power plug in/out of battery
  • battery.onchargingtimechange : to detect change in battery level
  • battery.onlevelchange : to detect change in battery level

In the below example as soon as the battery level goes below 15% an alert will popup recommending connecting system to charger .

Read full article here 👉 https://bepractical.tech/how-to-check-battery-status-with-javascript-2-simple-steps/

Top comments (0)

🌚 Life is too short to browse without dark mode