Chapter 14. Device Integration

Introduction

The modern web browser platform includes APIs to interact with all kinds of device information and capabilities, including:

  • Battery status

  • Network status

  • Geolocation

  • Device clipboard

  • Sharing content

  • Tactile feedback

At the time of writing, some of these APIs are not well supported yet. Some are still considered experimental, so you shouldn’t use them in a production application just yet.

Some of these APIs may be supported by a given browser, like Chrome, but still won’t work if the device is missing the required capabilities. For example, the Vibration API is well supported by Chrome, but won’t work on a laptop or other device without vibration support.

Reading the Battery Status

Problem

You want to show the device’s battery charging status in your app.

Solution

Use the Battery Status API.

Note

This API may not be supported by all browsers yet. See CanIUse for the latest compatibility data.

You can query the Battery Status API by calling navigator.getBattery. This method returns a Promise that resolves to an object containing battery information.

First, write some HTML placeholder elements to hold the battery status, as shown in Example 14-1.

Example 14-1. The battery status markup
<ul>
  <li>Battery charge level:<span id="battery-level">--</span></li>
  <li>Battery charge status:<span id="battery-charging">--</span></li>
</ul>

Then, you can query the Battery Status API to get the battery charge level and charging ...

Get Web API Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.