Web API Battery Events
- chargingchange: Fires when the device’s charging status changes.
- chargingtimechange: Fires when the estimated time until full charge changes.
- dischargingtimechange: Fires when the estimated time until battery depletion changes.
- levelchange: Fires when the battery level changes.
Example: In this example we are using every event and method.
HTML
<!DOCTYPE html> < html > < head > < title >Web API Battery Example</ title > </ head > < body > < h1 >Battery Information</ h1 > < p id = "battery-level" >Battery Level: N/A</ p > < p id = "charging-status" >Charging: N/A</ p > < p id = "charging-time" >Charging Time: N/A</ p > < p id = "discharging-time" >Discharging Time: N/A</ p > < script > // Check if the Battery API is supported in // the current browser if ('getBattery' in navigator || 'battery' in navigator) { // Use navigator.getBattery() if available (newer browsers) const batteryPromise = navigator.getBattery ? navigator.getBattery() : navigator.battery; batteryPromise.then(function (battery) { // Display battery information updateBatteryInfo(battery); // Add event listeners for battery status changes battery.addEventListener('chargingchange', function () { updateBatteryInfo(battery); }); battery.addEventListener('chargingtimechange', function () { updateBatteryInfo(battery); }); battery.addEventListener('dischargingtimechange', function () { updateBatteryInfo(battery); }); battery.addEventListener('levelchange', function () { updateBatteryInfo(battery); }); }); } else { // Battery API is not supported alert('Battery API is not supported in this browser.'); } // Function to update battery information on the page function updateBatteryInfo(battery) { document.getElementById('battery-level') .textContent = `Battery Level: ${battery.level * 100}%`; document.getElementById('charging-status') .textContent = `Charging: ${battery.charging ? 'Yes' : 'No'}`; document.getElementById('charging-time') .textContent = `Charging Time: ${battery.chargingTime} seconds`; document.getElementById('discharging-time') .textContent = `Discharging Time: ${battery.dischargingTime} seconds`; } </ script > </ body > </ html > |
Output:
Web API Battery
Web API Battery is a JavaScript API that enables web applications to retrieve and track information about the device’s battery status. This information includes the battery’s charging status, level, and whether the device is currently charging or discharging. By utilizing this API, web developers can optimize their applications for energy efficiency and enhance the user experience.