HTML5 - Unknown JavaScript Web APIs

· 1 min

HTML5 can do a lot of cool things, like saving data in local storage or getting a user's location for a custom Google map. It turns out there are many more JavaScript APIs that I haven't seen people mention. Here are a few, focusing on ones that benefit mobile and tablet devices.

Online state

A web app can now tell whether the user has an internet connection. That's useful for apps that stream data in: instead of showing nothing, they can tell the user there's a connection problem, which is a much better experience.

The API is being extended. Reading the connection speed and adapting the app, for example by lowering image quality, would be useful.

window.addEventListener('offline', networkStatus);
window.addEventListener('online', networkStatus);
function networkStatus(e) {
  console.log(e);
}

Support

Support is excellent in recent browsers, including some smaller device-specific ones such as Samsung Internet.

Device orientation

An easy way to find the orientation of a device. It's especially useful for media-heavy web apps, so content can make the most of the space in each orientation. Combined with CSS, it can also rotate images in 3D space.

window.addEventListener('deviceorientation', (e) => {
console.log('alpha:', e.alpha);
console.log('beta:', e.beta); 
console.log('gamma:', e.gamma);
});

Support

Support isn't great: partial, with known issues. Fine for fun, non-essential features, but I wouldn't rely on it.

Ambient light

This one is really cool. It returns the light level in lux, from the Generic Sensor API. One use is switching to a darker or lighter theme depending on the light, ideally letting the user opt in.

window.addEventListener('devicelight', (e) => {
  console.log(`${e.value} lux`);
})

Support

Support is bad. It's in Chrome from version 62, but as an experimental feature you have to enable.

Battery level

A web app can now read the battery level, and whether the device is plugged in. The API is a little different in that it returns a promise. This example is one of the W3C's:

navigator.getBattery().then(function(battery) {
  console.log(battery.level);
  battery.addEventListener('levelchange', function() {
    console.log(this.level);
  });
});

Support

Support is poor unless you're only targeting Chrome, and since Firefox has removed it, the future doesn't look promising.