JavaScript Navigator getBattery() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs

What You’ll Learn

navigator.getBattery() is the entry point to the Battery Status API. Learn how to get a BatteryManager, read charging and level, listen for chargingchange, use HTTPS, and try five beginner examples.

01

Kind

Method

02

Returns

Promise<BatteryManager>

03

Status

Limited availability

04

Context

Secure (HTTPS)

05

API family

Battery Status API

06

Key fields

charging · level

Introduction

Laptops and phones have a battery. Your page can optionally read a simple status snapshot — is it charging? how full is it? — through navigator.getBattery().

The method does not return the numbers directly. It returns a Promise that resolves to a BatteryManager object. From there you read properties and listen for change events.

💡
Use for UX, not tracking

Good uses: pause heavy animations on low battery, show a gentle “plug in” hint. Bad uses: fingerprinting or forcing behavior when the API is missing.

Understanding the getBattery() Method

  • No parameters — call navigator.getBattery().
  • Resolves to BatteryManager — properties include charging, level, chargingTime, dischargingTime.
  • Events — e.g. chargingchange, levelchange, time-change events.
  • Secure context — HTTPS / localhost required in modern Chromium.
  • Permissions-Policy — may be gated by the battery directive.
  • Limited support — missing in some browsers for privacy; always feature-detect.

📝 Syntax

General form of the method:

JavaScript
navigator.getBattery()

Parameters

  • None.

Return value

  • A Promise that fulfills with a BatteryManager object.

Common patterns

JavaScript
// MDN: track charging state
let batteryIsCharging = false;

navigator.getBattery().then((battery) => {
  batteryIsCharging = battery.charging;

  battery.addEventListener("chargingchange", () => {
    batteryIsCharging = battery.charging;
  });
});

// Async / await with feature detect
async function readBatterySnapshot() {
  if (!navigator.getBattery) return null;
  const battery = await navigator.getBattery();
  return {
    charging: battery.charging,
    levelPercent: Math.round(battery.level * 100)
  };
}

⚡ Quick Reference

GoalCode
Feature detecttypeof navigator.getBattery === "function"
Get managerconst battery = await navigator.getBattery()
Charging?battery.charging
Level 0–1battery.level
Listen for plug/unplugbattery.addEventListener("chargingchange", …)
Secure context?window.isSecureContext

🔍 At a Glance

Four facts to remember about navigator.getBattery().

Returns
Promise

BatteryManager

Availability
Limited

Not Baseline

Context
HTTPS

Secure required

Level
0.0–1.0

Multiply by 100

📋 BatteryManager Properties

PropertyMeaning
chargingBoolean — currently charging?
levelNumber 0–1 — remaining charge fraction
chargingTimeSeconds until full (or Infinity / 0 depending on state)
dischargingTimeSeconds until empty (or Infinity when charging / unknown)

Examples Gallery

Examples follow MDN Battery Status API patterns. Prefer Try It Yourself — many browsers omit the API, and desktops without a battery may report always-charging / full.

📚 Getting Started

Detect the API and read charging state like MDN.

Example 1 — Feature Detection

Check support and secure context before calling.

JavaScript
const lines = [
  "getBattery: " +
    (typeof navigator.getBattery === "function" ? "available" : "missing"),
  "isSecureContext: " + window.isSecureContext
];
console.log(lines.join("\n"));
Try It Yourself

How It Works

If the method is missing, skip battery UX and keep the app fully usable.

Example 2 — Read Charging State (MDN)

MDN’s basic pattern: store battery.charging and update on change.

JavaScript
let batteryIsCharging = false;

if (!navigator.getBattery) {
  console.log("getBattery not supported");
} else {
  navigator.getBattery().then((battery) => {
    batteryIsCharging = battery.charging;
    console.log("charging: " + batteryIsCharging);

    battery.addEventListener("chargingchange", () => {
      batteryIsCharging = battery.charging;
      console.log("charging changed: " + batteryIsCharging);
    });
  }).catch((err) => {
    console.log("getBattery error: " + err.name);
  });
}
Try It Yourself

How It Works

Always .catch — Permissions-Policy or insecure context can reject.

📈 Practical Patterns

Read level percent, listen for updates, and react to low battery.

Example 3 — Battery Level Percent

Convert level (0–1) into a friendly percentage.

JavaScript
async function getLevelPercent() {
  if (!navigator.getBattery) return "getBattery not supported";
  try {
    const battery = await navigator.getBattery();
    return "level: " + Math.round(battery.level * 100) + "%";
  } catch (err) {
    return "Error: " + err.name;
  }
}

getLevelPercent().then(console.log);
Try It Yourself

How It Works

Listen to levelchange if you show a live percentage in the UI.

Example 4 — Snapshot + Listeners

Log a full snapshot and attach common BatteryManager events.

JavaScript
async function watchBattery() {
  if (!navigator.getBattery) return "getBattery not supported";
  const battery = await navigator.getBattery();
  const snapshot = () =>
    "charging=" + battery.charging +
    " level=" + Math.round(battery.level * 100) + "%";

  console.log("initial: " + snapshot());
  battery.addEventListener("chargingchange", () => {
    console.log("chargingchange: " + snapshot());
  });
  battery.addEventListener("levelchange", () => {
    console.log("levelchange: " + snapshot());
  });
  return "Listening for chargingchange + levelchange";
}

watchBattery().then(console.log);
Try It Yourself

How It Works

Remove listeners when your component unmounts to avoid leaks in SPAs.

Example 5 — Low-Battery Soft Mode

Beginner UX helper: suggest reducing work when charge is low and not charging.

JavaScript
async function shouldUsePowerSaver(threshold = 0.2) {
  if (!navigator.getBattery) {
    return { powerSaver: false, reason: "unsupported" };
  }
  try {
    const battery = await navigator.getBattery();
    const low = battery.level <= threshold && !battery.charging;
    return {
      powerSaver: low,
      reason: low ? "low-battery" : "ok",
      levelPercent: Math.round(battery.level * 100),
      charging: battery.charging
    };
  } catch (err) {
    return { powerSaver: false, reason: err.name };
  }
}

shouldUsePowerSaver().then((result) => {
  console.log(JSON.stringify(result));
});
Try It Yourself

How It Works

Treat power-saver as optional: never break core features when battery data is unavailable.

🚀 Common Use Cases

  • Power-aware demos — reduce animations when charge is low.
  • Status chips — optional “Charging” / percent indicator in tools apps.
  • Background sync hints — delay heavy sync until plugged in.
  • Learning Battery Status API — explore BatteryManager events safely.
  • Progressive enhancement — app works fully without battery access.

🧠 How navigator.getBattery() Works

1

Detect + secure page

Confirm getBattery exists on HTTPS / localhost.

Detect
2

Await the Promise

Receive a BatteryManager (or catch a policy / security error).

Resolve
3

Read charging & level

Use properties for a snapshot; listen for change events.

Observe
4

Adapt UX gently

Optional power-saver hints — never hard-require battery data.

📝 Notes

  • Limited availability (not Baseline) — feature-detect always.
  • Not Deprecated, Experimental, or Non-standard — no status banner required (MDN).
  • Secure context required in modern Chromium (HTTPS / localhost).
  • May be blocked by Permissions-Policy battery (NotAllowedError).
  • Related: getGamepads(), getAutoplayPolicy(), connection, Window.

Limited Availability Support

navigator.getBattery() implements the Battery Status API and is not Baseline. Chromium browsers support it in secure contexts; Firefox removed it for privacy; Safari support is limited or absent. Always feature-detect, use HTTPS, and keep core UX independent of battery data.

Limited availability · Not Baseline

Navigator.getBattery()

Promise → BatteryManager — charging, level, and change events.

Limited Not Baseline
Google Chrome Battery Status · secure context (from Chrome 103)
Limited
Microsoft Edge Follow Chromium Battery Status / HTTPS
Limited
Opera Follow Chromium where available
Limited
Mozilla Firefox Removed for privacy — feature-detect
Unavailable
Apple Safari Typically unavailable — feature-detect
Unavailable
Internet Explorer No Battery Status / getBattery
Unavailable
getBattery() Limited

Bottom line: Detect getBattery, await BatteryManager on HTTPS, handle rejections, and never require battery status for essential features.

Conclusion

navigator.getBattery() opens the Battery Status API with a Promise for a BatteryManager. Detect support, use HTTPS, read charging and level, listen for changes, and treat battery insights as optional UX — never as a hard dependency.

Continue with getGamepads(), getAutoplayPolicy(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Feature-detect navigator.getBattery
  • Use HTTPS / localhost
  • Handle Promise rejections
  • Use battery data for gentle power-saving UX
  • Remove event listeners when done

❌ Don’t

  • Assume Baseline support
  • Require battery access for core features
  • Use battery data for fingerprinting
  • Ignore secure-context / Permissions-Policy failures
  • Block the UI waiting on battery alone

Key Takeaways

Knowledge Unlocked

Five things to remember about getBattery()

Promise → BatteryManager — optional power-aware UX.

5
Core concepts
02

Availability

Limited

Not Baseline
🔒 03

Context

secure HTTPS

Required
🔌 04

Fields

charging · level

Status
🎯 05

Use

optional UX

Privacy

❓ Frequently Asked Questions

It returns a Promise that resolves to a BatteryManager object with charging state, battery level (0–1), charging/discharging times, and events such as chargingchange and levelchange.
No. MDN does not mark it Deprecated, Experimental, or Non-standard. It is Limited availability (not Baseline), requires a secure context in modern Chrome, and may be missing for privacy reasons in some browsers. No status banner is required.
Yes in supporting Chromium browsers since Chrome 103: getBattery() is a secure-context feature (HTTPS or localhost). Calling it from an insecure context can throw SecurityError.
A number from 0.0 to 1.0 representing remaining charge — for example 0.75 means about 75%.
No. Desktops without a battery, privacy-restricted browsers (notably Firefox removed the API), and missing Permissions-Policy: battery can block or omit it. Always feature-detect and handle Promise rejection.
No. Battery status is for helpful UX (pause heavy work on low battery), not fingerprinting. Prefer privacy-respecting, optional enhancements.
Did you know?

On many desktop machines without a battery (or with the OS reporting “always plugged in”), charging may stay true and level may stay at 1. Always treat those values as hints, not absolute truth.

Explore getGamepads() Next

Read controller buttons and axes for browser games.

getGamepads() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful