Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 721
KingCoder11 Avatar asked Jun 10 '17 09:06

KingCoder11


People also ask

How do I find out the battery level?

Check battery life & useOpen your phone's Settings app. Under "Battery," see how much charge you have left, and about how long it will last. For details, tap Battery. For a graph and list of battery use, tap Battery Usage.

What is battery Status API?

The Battery Status API, more often referred to as the Battery API, provides information about the system's battery charge level and lets you be notified by events that are sent when the battery level or charging status change.

How do you check battery life on iPhone?

Go to Settings > Battery, then turn on Battery Percentage. On an iPhone with Face ID, the battery percentage appears inside the battery symbol on the status bar. Tip: On iPhone models with Face ID, you can also swipe down from the top-right corner to quickly view the battery percentage in Control Center.


1 Answers

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)+"%");
});
like image 169
Erik Lumme Avatar answered Oct 08 '22 01:10

Erik Lumme