Javascript is required
Mokkapps LogoMichael Hoffmann

JavaScript Tip: Get Valuable Info About Device Battery

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Jan 9, 2023
1 min read
|
27 views
Javascript
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
navigator.getBattery().then((battery) => {  console.log(`Battery level: ${Math.round(battery.level * 100)}%`)  // Battery level: 57%  console.log(`Battery discharging time: ${battery.dischargingTime / 60} minutes`)  // Battery discharging time: 179 minutes})

If you liked this tip, follow me on Twitter to get notified about new tips, blog posts, and more.