| 1 | (function() { |
| 2 | 'use strict'; |
| 3 | |
| 4 | var battery; |
| 5 | |
| 6 | function toTime(sec) { |
| 7 | sec = parseInt(sec, 10); |
| 8 | |
| 9 | var hours = Math.floor(sec / 3600), |
| 10 | minutes = Math.floor((sec - (hours * 3600)) / 60), |
| 11 | seconds = sec - (hours * 3600) - (minutes * 60); |
| 12 | |
| 13 | if (hours < 10) { hours = '0' + hours; } |
| 14 | if (minutes < 10) { minutes = '0' + minutes; } |
| 15 | if (seconds < 10) { seconds = '0' + seconds; } |
| 16 | |
| 17 | return hours + ':' + minutes; |
| 18 | } |
| 19 | |
| 20 | function readBattery(b) { |
| 21 | battery = b || battery; |
| 22 | |
| 23 | var percentage = parseFloat((battery.level * 100).toFixed(2)) + '%', |
| 24 | fully, |
| 25 | remaining; |
| 26 | |
| 27 | if (battery.charging && battery.chargingTime === Infinity) { |
| 28 | fully = 'Calculating...'; |
| 29 | } else if (battery.chargingTime !== Infinity) { |
| 30 | fully = toTime(battery.chargingTime); |
| 31 | } else { |
| 32 | fully = '---'; |
| 33 | } |
| 34 | |
| 35 | if (!battery.charging && battery.dischargingTime === Infinity) { |
| 36 | remaining = 'Calculating...'; |
| 37 | } else if (battery.dischargingTime !== Infinity) { |
| 38 | remaining = toTime(battery.dischargingTime); |
| 39 | } else { |
| 40 | remaining = '---'; |
| 41 | } |
| 42 | |
| 43 | document.styleSheets[0].insertRule('.battery:before{width:' + percentage + '}', 0); |
| 44 | document.querySelector('.battery-percentage').innerHTML = percentage; |
| 45 | document.querySelector('.battery-status').innerHTML = battery.charging ? 'Adapter' : 'Battery'; |
| 46 | document.querySelector('.battery-level').innerHTML = percentage; |
| 47 | document.querySelector('.battery-fully').innerHTML = fully; |
| 48 | document.querySelector('.battery-remaining').innerHTML = remaining; |
| 49 | |
| 50 | } |
| 51 | |
| 52 | if (navigator.battery) { |
| 53 | readBattery(navigator.battery); |
| 54 | |
| 55 | } else if (navigator.getBattery) { |
| 56 | navigator.getBattery().then(readBattery); |
| 57 | |
| 58 | } else { |
| 59 | document.querySelector('.not-support').removeAttribute('hidden'); |
| 60 | } |
| 61 | |
| 62 | window.onload = function () { |
| 63 | battery.addEventListener('chargingchange', function() { |
| 64 | readBattery(); |
| 65 | }); |
| 66 | |
| 67 | battery.addEventListener("levelchange", function() { |
| 68 | readBattery(); |
| 69 | }); |
| 70 | }; |
| 71 | }()); |