Search code examples
javascriptbattery

How can I get the devices battery level in javascript


I am doing a network call every 15 seconds in my app, and if the users device battery percent is lower than 20%, than I would like to do the call every 30 seconds instead. How do I get the user's devices current battery level? Is it possible? Any help would be appreciated.


Solution

  • Take a look at the Battery Status API. It doesn't work in all browsers, but it's a start.

    For browsers that support it, something like this should work:

    navigator.getBattery().then(function(battery) {
      battery.addEventListener('levelchange', function() {    
        // Do stuff when the level changes, you can get it
        // from battery.level
        document.write((battery.level*100)+"%");
      })
      document.write((battery.level*100)+"%");
    });