5 JavaScript APIs to Empower Your Mobile Web Pages

Statements like

“The mobile market is increasing”

and

“People accessing the web through a mobile device (smartphones, tablets etc.) will overtake those accessing it through a desktop or a laptop”

don’t impress anymore.

Today we’re all aware, at least we should be, that the mobile market is significant when developing anything for the web.

For years there has been discussion and differing points of view about native applications versus web applications and on which is the best. Regardless of your opinion, it used to be a fact that native mobile applications allowed to access hardware components that web pages couldn’t. But is this gap still valid today? Have web technologies improved to the point where we, as developers, can code with just HTML, CSS, and JavaScript?

In this article I’ll introduce some JavaScript APIs that allow your web pages to access hardware components of mobile devices or that can empower your web application on mobile devices.

Battery Status API

The Battery Status API provides information about the system’s battery level or status. Thanks to this API you are able to know if the battery is charging or not, how long before the battery will be fully discharged, or simply its current level. These details are accessible through four properties that all belong to the window.navigator.battery object. This API also defines events that can be fired when there are changes in the mentioned properties.

This API is useful in cases such as where you (or your users) are on a bus working hard on a document using a web application and forgot to save the changes you made. Suddenly, your smartphone shuts down and you go crazy because you have lost a lot of time and all your work. Thanks to this API we can develop pages able to detect the current level of the battery and save changes more frequently to prevent data loss in case it’s low or critical.

At the time of writing the Battery Status API is only supported by Firefox but detecting support for this API is easy and is shown below:

if (window.navigator && window.navigator.battery) {
   // API supported
} else {
   // Not supported
}

A simple example of using this API is the following:

// Print if battery is charging or not
console.log("The battery is " + (navigator.battery.charging ? "" : "not") + " charging");

If you want to experiment with this API, we have a demo just for you. If you want to investigate further, we have covered the Battery Status API here at SitePoint.

Web Notifications API

On mobile devices we’re familiar with the concept of notifications, they are implemented by many apps that we have installed on our devices. On the web, websites implement them in different ways. Think of Google+ and Twitter, they both have a notification mechanism but the implementations are different.

The Web Notifications API is an API created with this aim, to standardize the way developers notify users. A notification allows alerting a user outside the context of a web page of an event, such as the delivery of email. While the way developers can create a notification is the same, the specifications don’t describe how and where a UI should display them. This means that we’ll see different styles on different browsers. For example on mobile devices we may see them in the notifications bar.

The Web Notifications API is exposed through the Notification property of the window object. It’s a constructor that allows us to create a notification instance. To create a new notification, we can write code like the following:

var notification = new Notification('Email received', {
  body: 'You received an email. Read it. Now!'
});

Currently, the API is supported by Chrome, Firefox, and Safari. The mobile browsers that support the Web Notifications API are Firefox, Android 4.4+, and Blackberry. Do you see something weird? Chrome mobile doesn’t support the API! Sad but true.

Due to the browsers that do support this API, more than half the market is covered but because we want to be sure our JavaScript code doesn’t try to call unsupported methods, we have to test for support. We can do that employing the following snippet:

if ('Notification' in window) {
  // API supported
} else {
  // Not supported
}

Excited by this API? Great! You can read more about it in the article “An Introduction to the Web Notifications API” and also play with a live demo.

Proximity API

The Proximity API is a JavaScript API that we can use to detect the proximity of an object to the device where the web page is running. The distance is measured by a proximity sensor, if your device has one. The Proximity API doesn’t provide properties or methods, only two events fired on the window object. We can listen for them to perform operations. The first event, deviceproximity, provides information about the actual distance between the device and a nearby object, while the second event, userproximity, only specifies if there is an object nearby.

The only browser that supports this API is Firefox, both on desktop and mobile, starting from version 15. Unfortunately, because many laptops and desktops don’t have a proximity sensor, we have to target mainly mobile devices.

To detect support for this API:

if ('ondeviceproximity' in window) {
   // API supported
} else {
   // Not supported
}

A simple example of use is shown below:

window.addEventListener('userproximity', function(event) {
   console.log( (event.near ? '' : 'no ') + 'object detected nearby');
});

If you want to read more about the Proximity API, I wrote an article titled “Introducing the Proximity API“. In case you want to see it in action, you can play with this demo.

Vibration API

The Vibration API is a very simple API, consisting of one method that gives us the power to vibrate a device. One obvious use is in games where we can recreate effects introduced a decade ago by some consoles. However, this isn’t the only possible use of this API.

As I mentioned, the Vibration API exposes only one method called vibrate(). The latter belongs to the window.navigator object and accepts, in its simplest form, an integer that specifies the number of milliseconds the device should vibrate.

This API is supported by all major browsers except Internet Explorer and Safari. Despite this, it may be the right time to use it in your next project. In fact, if it’s supported, you’ll offer your users a better experience (unless you abuse of this feature, of course). Detecting for support is very easy and it’s shown below:

if (window.navigator && window.navigator.vibrate) {
   // API supported
} else {
   // Not supported
}

A very simple use of the API is the following:

// Vibrate for three seconds
navigator.vibrate(3000);

To learn more about this API read the article “How to Use the HTML5 Vibration API” and don’t forget to play with the demo.

Device Orientation API

The last API I want to discuss is the Device Orientation API. Detecting the orientation of a device is useful for a wide range of cases, from navigation applications to games. This API defines several events that provide information about the physical orientation and motion of a device. This API is a W3C Working Draft, which means the specification isn’t stable and we may expect some changes in the future.

The API exposes the following three events deviceorientation, devicemotion and compassneedscalibration. The first is fired when the accelerometer detects a change of the device orientation. The second is triggered every time the device accelerates or decelerates. The last event is fired when the user agent determines the compass requires calibration.

This API is supported by almost every major browser (except Safari) but the support is partial or has inconsistencies. For example, at the time of writing, very few browsers support the compassneedscalibration event. So, my advice is to test for each of these events to know if it’s supported. To test for the presence of the deviceorientation event you can write:

if (window.DeviceOrientationEvent) {
   // Event supported
} else {
   // Not supported
}

or alternatively:

if ('ondeviceorientation' in window) {
   // Event supported
} else {
   // Not supported
}

If, for example, you want to test for the devicemotion event, you can write:

if (window.DeviceMotionEvent) {
   // Event supported
} else {
   // Not supported
}

In case you want to play with this API we have a demo that you can use. If you want to study it, we have the article “Using Device Orientation in HTML5“.

Conclusions

In this article I showed you some APIs that can empower your web pages for mobile visitors.

The use cases for these APIs are endless and it all depends on your fantasy and the type of application or website you’re developing. I hope you enjoyed this article, let me know of any other APIs you think may be useful.

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • Christian Heilmann

    All the code examples are double encoded here.

    • Aurelio De Rosa

      Hello Christian.

      Thank you very much for the feedback. I already noted this issue and I’ve notified the editor. I’m sure he’ll fix it soon.

    • Chris Ward

      Not sure how I missed that guys, apologies and fixed up :)

  • CTN

    5 do nothing useless APIs. thanks.

    • http://www.trivial.ly/ Nic Johnson

      That comment makes no sense.

  • http://www.trivial.ly/ Nic Johnson

    I’m particularly interested in the notifications api. Deeper device integration is handy. You might also mention the camera api.

  • WebReflection

    typo: if (!(‘ondeviceorientation’ in window)) shold probably be if(‘ondeviceorientation’ in window)

    • Aurelio De Rosa

      You’re right. I’ll notify @chrischinchilla:disqus.

  • Ralph Mason

    Nice article. And thanks so much for not calling these “HTML5 APIs”! “JavaScript APIs” or “browser APIs” is much more accurate.

    • Aurelio De Rosa

      Hi Ralph. I see your point here, but I must admit that sometimes is hard to distinguish between APIs that are part of the HTML5 specs and APIs that are not. So, I really don’t care too much if someone would point to them as HTML5 APIs.

  • Aurelio De Rosa
  • Surendra Vikram Singh

    Yeeee!!! I made my homepage vibrate :)

    • Aurelio De Rosa

      I’m glad you liked it :)