·
1 min read

JavaScript Tip: Get Valuable Info About Device Battery

JavaScript Tip: Get Valuable Info About Device Battery Image

The Battery Status API provides information about the system's battery charge level and lets you be notified by events sent when the battery level or charging status changes.

Knowing a device's battery status can be helpful in several situations or use cases. Here are some examples:

  • Save the application state before the battery runs out to prevent data loss.
  • Pause heavy computations/animations when the battery is low.
  • For example, an email client may check the server for new emails less frequently if the device is low on battery.
  • Switch to dark mode when the battery is low, which can save energy.

Let's take a look at a simple example to get the device's battery status:

battery.js
1navigator.getBattery().then((battery) => {
2  console.log(`Battery level: ${Math.round(battery.level * 100)}%`)
3  // Battery level: 57%
4
5  console.log(`Battery discharging time: ${battery.dischargingTime / 60} minutes`)
6  // Battery discharging time: 179 minutes
7})