Key Takeaways
- The Battery Status API can provide information about a device’s battery level or status, which can be used to save changes more frequently to prevent data loss when the battery level is low.
- The Web Notifications API standardizes how developers notify users, allowing for alerts outside the context of a web page, such as email delivery. However, the API’s display styles may vary across different browsers.
- The Proximity API can detect the proximity of an object to the device where the web page is running, although it’s currently only supported by Firefox.
- The Vibration API allows a device to vibrate, which can be useful in games to recreate certain effects. The Device Orientation API, on the other hand, detects the orientation of a device, which can be beneficial for navigation applications and games.
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.
Frequently Asked Questions about JavaScript APIs for Mobile Web Pages
What are JavaScript APIs and how do they empower mobile web pages?
JavaScript APIs (Application Programming Interfaces) are sets of rules and protocols that allow different software applications to communicate with each other. They empower mobile web pages by enabling them to interact with device hardware and other software applications, thereby enhancing their functionality and user experience. For instance, JavaScript APIs can allow a web page to access a device’s camera, geolocation, or even its battery status. This opens up a world of possibilities for developers to create more interactive, engaging, and user-friendly mobile web pages.
How can I use the Geolocation API in my mobile web page?
The Geolocation API is a powerful tool that allows you to access the geographical location of a device. To use it, you first need to check if the user’s browser supports it. This can be done using the ‘navigator.geolocation’ property. If it returns ‘true’, then you can use the ‘getCurrentPosition()’ method to get the user’s current location. Remember to always ask for the user’s permission before accessing their location data.
What is the Battery Status API and how can it be used?
The Battery Status API provides information about the battery status of the hosting device. This can be useful for optimizing the performance of your web page based on the device’s battery level. For instance, you could reduce the frequency of updates or disable certain features when the battery level is low to conserve power. To use this API, you can use the ‘navigator.getBattery()’ method which returns a promise that resolves to a BatteryManager object.
How can I use the Vibration API in my mobile web page?
The Vibration API allows you to control the vibration mechanism of the hosting device. This can be useful for providing tactile feedback to the user. To use this API, you can use the ‘navigator.vibrate()’ method. You can pass a single value to vibrate for a specific amount of time, or an array of values to create a pattern of vibrations and pauses.
What is the Ambient Light Sensor API and how can it be used?
The Ambient Light Sensor API provides information about the ambient light level of the device’s environment. This can be useful for adjusting the brightness or contrast of your web page to improve readability under different lighting conditions. To use this API, you need to create a new instance of the ‘AmbientLightSensor’ object and then use the ‘start()’ method to start sensing the light level.
How can I use the Network Information API in my mobile web page?
The Network Information API provides information about the device’s network connection. This can be useful for optimizing your web page’s performance based on the network conditions. For instance, you could reduce the quality of images or videos when the network connection is slow to ensure smooth loading. To use this API, you can use the ‘navigator.connection’ property which returns a NetworkInformation object.
What is the Device Orientation API and how can it be used?
The Device Orientation API provides information about the physical orientation of the device. This can be useful for creating interactive experiences that respond to the device’s movements. To use this API, you can add an event listener for the ‘deviceorientation’ event which fires whenever the device’s orientation changes.
How can I use the Page Visibility API in my mobile web page?
The Page Visibility API allows you to detect when a web page becomes visible or hidden. This can be useful for pausing or resuming activities based on the visibility of the page. For instance, you could pause a video when the user switches to a different tab and resume it when they return. To use this API, you can use the ‘document.visibilityState’ property and the ‘visibilitychange’ event.
What is the Fullscreen API and how can it be used?
The Fullscreen API allows you to display an element in fullscreen mode. This can be useful for providing a more immersive experience for things like videos or games. To use this API, you can use the ‘requestFullscreen()’ method on any element to make it fullscreen.
How can I use the Web Notifications API in my mobile web page?
The Web Notifications API allows you to display notifications to the user. This can be useful for alerting the user to important events, even when your web page is not in focus. To use this API, you first need to ask for the user’s permission using the ‘Notification.requestPermission()’ method. If the user grants permission, you can then create a new Notification object to display a notification.
I'm a (full-stack) web and app developer with more than 5 years' experience programming for the web using HTML, CSS, Sass, JavaScript, and PHP. I'm an expert of JavaScript and HTML5 APIs but my interests include web security, accessibility, performance, and SEO. I'm also a regular writer for several networks, speaker, and author of the books jQuery in Action, third edition and Instant jQuery Selectors.