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.
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.
Share Improve this question asked Nov 17, 2024 at 12:50 baranwalayushbaranwalayush 11 bronze badge 3 |1 Answer
Reset to default 0You 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.
navigator.battery()
and print out the currentbattery level
. It seems, we need more debugging information from your side. I will post my minimal, (hopefully) reproducible example and would like to ask you to test it and share your observations. – Markus Commented Nov 17, 2024 at 20:47