Getting started with JavaScriptFunctionsArraysObjectsAJAXClassesArithmetic (Math)Comparison OperationsConditionsLoopsPromisesRegular expressionsDateError HandlingGeolocationCookiesIntervals and TimeoutsGeneratorsHistoryStrict modeCustom ElementsJSONBinary DataTemplate LiteralsWeb StorageFetchScopeModulesScreenInheritanceTimestampsDestructuring assignmentWorkersVariable coercion/conversionDebuggingNotifications APIBuilt-in ConstantsWebSocketsWeb Cryptography APIAsync functions (async/await)StringsConstructor functionsexecCommand and contenteditablePerformance TipsMapCreational Design PatternsrequestAnimationFrameReserved KeywordsMethod ChainingGlobal error handling in browsersUnary OperatorsFile API, Blobs and FileReadersCommentsConsoleTail Call OptimizationDetecting browserEnumerationsSymbolsLocalizationSelection APICallbacksSetDeclarations and AssignmentsFunctional JavaScriptModals - PromptsData attributesThe Event LoopBattery Status APIData ManipulationBitwise operatorsTranspilingBOM (Browser Object Model)Unit Testing JavascriptLinters - Ensuring code qualityAutomatic Semicolon Insertion - ASIIndexedDBAnti-patternsNavigator ObjectModularization TechniquesProxySame Origin Policy & Cross-Origin CommunicationArrow Functions.postMessage() and MessageEventWeakMapWeakSetEscape SequencesBehavioral Design PatternsServer-sent eventsAsync IteratorsNamespacingEvaluating JavaScriptMemory efficiencyDate ComparisonHow to make iterator usable inside async callback functionContext (this)Setters and GettersVibration APIPrototypes, objectsDatatypes in JavascriptBitwise Operators - Real World Examples (snippets)Fluent APITilde ~Security issuesUsing javascript to get/set CSS custom variablesJavaScript VariablesEvents

Battery Status API

Other topics

Remarks:

  1. Note that the Battery Status API is no longer available due to privacy reasons where it could be used by remote trackers for user fingerprinting.

  2. The Battery Status API is an Application Programming Interface for the client's battery status. It provides information on:

    • battery charging state via 'chargingchange' event and battery.charging;
    • battery level via 'levelchange' event and battery.level;
    • charging time via 'chargingtimechange' event and battery.chargingTime;
    • discharging time via 'dischargingtimechange' event and battery.dischargingTime.
  3. MDN Docs: https://developer.mozilla.org/en/docs/Web/API/Battery_status_API

Getting current battery level

// Get the battery API
navigator.getBattery().then(function(battery) {
    // Battery level is between 0 and 1, so we multiply it by 100 to get in percents
    console.log("Battery level: " + battery.level * 100 + "%");
});

Is battery charging?

// Get the battery API
navigator.getBattery().then(function(battery) {
    if (battery.charging) {
        console.log("Battery is charging");
    } else {
        console.log("Battery is discharging");
    }
});

Get time left until battery is empty

// Get the battery API
navigator.getBattery().then(function(battery) {
    console.log( "Battery will drain in ", battery.dischargingTime, " seconds" );
});

Get time left until battery is fully charged

// Get the battery API
navigator.getBattery().then(function(battery) {
    console.log( "Battery will get fully charged in ", battery.chargingTime, " seconds" );
});

Battery Events

// Get the battery API
navigator.getBattery().then(function(battery) {
    battery.addEventListener('chargingchange', function(){
        console.log( 'New charging state: ', battery.charging );
    });

    battery.addEventListener('levelchange', function(){
        console.log( 'New battery level: ', battery.level * 100 + "%" );
    });

    battery.addEventListener('chargingtimechange', function(){
        console.log( 'New time left until full: ', battery.chargingTime, " seconds" );
    });

    battery.addEventListener('dischargingtimechange', function(){
        console.log( 'New time left until empty: ', battery.dischargingTime, " seconds" );
    });
});

Contributors

Topic Id: 3263

Example Ids: 11201,11202,11203,11204,11205

This site is not affiliated with any of the contributors.