baranwalayush
baranwalayush

Reputation: 1

Alternative for navigator.getBattery() of battery api?

What should I use instead of navigator.getBattery(), as it is not working?

I am working on a chrome extension and with this what I want to do is -

function toggleBatterySaver(enable) {
  if (enable) {
      navigator.getBattery().then(battery => {
          if (battery.level < 0.2) {
              chrome.power.requestKeepAwake("system");
          }
      });
  } else {
      chrome.power.releaseKeepAwake();
  }
}

It is throwing an error: navigator.getBattery() is not a function.

Upvotes: 0

Views: 63

Answers (1)

Markus
Markus

Reputation: 6298

You can try to start with a minimal chrome extension that uses navigator.battery():

index.html:

<!DOCTYPE html>
<html>
<head><title>Battery Test</title></head>
<body><div id="bat">-</div></body>
<script src="script.js"></script>
</html>

script.js:

navigator.getBattery().then(battery => {
  document.getElementById("bat").innerHTML = "Battery: " + battery.level;
});

manifest.json:

{
    "name": "Battery Test",
    "version": "1.0.0",
    "description": "Battery Test",
    "manifest_version": 3,
    "author": "Markus",
    "action":{
        "default_popup": "index.html",
        "default_title": "Battery Test"
    }
}

Edit

In a service worker context the navigator object is of type WorkerNavigator that is missing the battery property among others. One way to get around this is to open an offscreen document.

manifest.json (set permission "offscreen"):

{
  "name": "Battery Test",
  "version": "1.0.0",
  "description": "Battery Test",
  "manifest_version": 3,
  "action":{
    "default_title": "Battery Test"
  },
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["offscreen"]
}

background.js (create the offscreen document "offscree.html"):

chrome.runtime.onInstalled.addListener(() => {
  chrome.offscreen.createDocument({
    url: 'offscreen.html',
    reasons: ['BATTERY_STATUS'],
    justification: 'read battery status'
  });
});

offscreen.html (runs your script):

<!DOCTYPE html>
<script src="script.js"></script>

script.js:

navigator.getBattery().then(battery => {
  console.log("Battery: " + battery.level);
});

If you need the battery status in the background process itself you can find features to send messages from the offscreen page to your worker and vice versa in the documention linked above.

Upvotes: 0

Related Questions