Zeratops Zeratops - 6 months ago 39
Javascript Question

Get battery level JavaScript

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

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
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.


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.


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