Skip to content
Advertisement

Get battery level JavaScript

/! THE USE OF window.navigator.battery IS STRONGLY DISCOURAGED AND THIS ISSUE IS NOW NOT WORTH CHECKING THANK YOU /!

I want to get the battery level of the current system. Here is the output I intend to get:

If desktop (no battery) Battery level : 100%

If laptop Battery level : XXX% (depending the level)

So I tried the snippet of the Mozilla Foundation over window.navigator.battery in my JSFiddle.

The problem : Running Chrome 20+ version (currently 46), I still have an error on the console :

Uncaught TypeError: Cannot read property ‘addEventListener’ of undefined

So what I understand is the object battery instantiated with the supposed battery level is returning nothing.

Did someone figured this out already ?

The point of my algorithm when this snippet works is to define which action the user cannot perform regarding the remaining battery level. For example, I don’t want the user to engage a heavy action that could probably lower his battery level to a critical point and make the critical action fail.

Advertisement

Answer

From the English version of that page:

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

and

The battery property is deprecated and has been replaced by a Navigator.getBattery() method returning a battery Promise. Its support is still partial though.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement