Last active
July 2, 2018 05:55
-
-
Save andreasvirkus/eb9936616ccd96889530b2c7266de2b2 to your computer and use it in GitHub Desktop.
Get navigator's battery data (current percentage, power source, usage time remaining and time to fully charge)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
let battery; | |
function toTime(sec) { | |
sec = parseInt(sec, 10) | |
let hours = Math.floor(sec / 3600) | |
let minutes = Math.floor((sec - (hours * 3600)) / 60) | |
let seconds = sec - (hours * 3600) - (minutes * 60) | |
if (hours < 10) hours = '0' + hours | |
if (minutes < 10) minutes = '0' + minutes | |
if (seconds < 10) seconds = '0' + seconds | |
return `${hours}:${minutes}` | |
} | |
function readBattery(b) { | |
battery = b || battery | |
const percentage = parseFloat((battery.level * 100).toFixed(2)) + '%' | |
let fully | |
let remaining | |
if (battery.charging && battery.chargingTime === Infinity) fully = 'Calculating...' | |
else if (battery.chargingTime !== Infinity) fully = toTime(battery.chargingTime) | |
else fully = '---' | |
if (!battery.charging && battery.dischargingTime === Infinity) remaining = 'Calculating...' | |
else if (battery.dischargingTime !== Infinity) remaining = toTime(battery.dischargingTime) | |
else remaining = '---' | |
const status = { | |
percentage, | |
status: battery.charging ? 'Adapter' : 'Battery', | |
time: fully, | |
remaining | |
} | |
console.table(status) | |
return status | |
} | |
if (navigator.battery) readBattery(navigator.battery) | |
else if (navigator.getBattery) navigator.getBattery().then(readBattery) | |
else console.warn('Battery API is not supported in your browser; please use Chrome') | |
window.onload = () => { | |
battery.addEventListener('chargingchange', () => readBattery()) | |
battery.addEventListener("levelchange", () => readBattery()) | |
} | |
}()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment