More Web APIs for PWAs

Joel Oliveira
Joel Oliveira
Mar 24 2023
Posted in Engineering & Technology

A few more tricks up your sleeve

More Web APIs for PWAs

With the imminent release of iOS 16.4, where Web Push is finally supported, we anticipate a renewed interest on this matter. And an important part of a great PWA, is the ability to behave, in many ways, just like a native app.

Many Web APIs that can make your PWA more native-like are not necessarily new, and we've already dedicated some posts, like this one, this one or this one to some of them. In this post, we will explore a few more and their ability to make your PWA behave like a native mobile app.

Screen Wake Lock API

This API allows developers to prevent the device screen from turning off automatically while their PWA is in use. This can be useful for apps that require the user's attention for an extended period of time, such as video players, games, or turn-by-turn navigation apps.

This API is currently supported on Chrome (84+), Edge (84+), Opera (70+) and Safari (16.4+). Only actively visible pages can request it, and it can be rejected for a number of reasons, including system settings, such as power save mode or low battery level.

To use it, it's always a good idea to check its availability:

if ("wakeLock" in navigator) {
  // It's supported
}

You can obtain a WakeLockSentinel object by using navigator.wakeLock.request():

let wakeLock = null;
try {
  wakeLock = await navigator.wakeLock.request("screen");
  // WakeLock is now active
} catch (err) {
  // Failed
}

You should also keep a reference to the WakeLockSentinel object, this will allow you to release it or re-acquire it if needed:

wakeLock.release();

wakeLock.addEventListener("release", () => {
  // WakeLock has been released
  wakeLock = null;
});

Because you can only request it when a page is visible, you should check for a visibility change before attempting to re-acquire a screen wake lock:

document.addEventListener("visibilitychange", async () => {
  if (wakeLock !== null && document.visibilityState === "visible") {
    wakeLock = await navigator.wakeLock.request("screen");
  }
});

Geolocation API

This Web API allows developers to retrieve the user's location information, such as latitude and longitude, using their device's GPS, Wi-Fi, or cellular network signals. With this information, we can build location-aware PWAs that provide customized content, services, and features based on the user's current location.

This API is supported by all modern browsers, but we should always check its availability using the following:

if ("geolocation" in navigator) {
  // It's supported
}

We can then request the current user's position, using:

navigator.geolocation.getCurrentPosition((position) => {
  console.log(`Latitude: ${position.coords.latitude} - Longitude: ${position.coords.longitude}`);
});

It is also possible to monitor changes in the user's location:

const monitorId = navigator.geolocation.watchPosition((position) => {
  console.log(`Latitude: ${position.coords.latitude} - Longitude: ${position.coords.longitude}`);
});

This will continuously update your web app with new coordinates as the user moves around. You can stop monitoring these changes using:

navigator.geolocation.clearWatch(monitorId);

Please note that both these methods work independently of each other, and will prompt a browser's permission dialogue (when invoked for the first time, if not authorized) which will only output results when users grant access to their location.

Badging API

This API allows developers to display badges, or small icons with numeric or textual content, on the app's icon in the device's home screen or taskbar. These badges can be used to show the user new messages, notifications, or other updates that require their attention.

A badge is set with the methods setAppBadge() (for installed apps), or setClientBadge() (for documents). If no parameters are passed to these methods then the badge value is flag. The user agent will display its notification badge, for example, a colored circle on the icon.

Because apps will only display a badge in certain conditions (installed/added to home screen), we should check for the existence of the method rather than the availability of the API.

if (navigator.setAppBadge) {
    navigator.setAppBadge(10);
} else {
  // Use alternative method
}

This method will work when invoked from a document or from a service worker. It may display on the app's icon in the dock, shelf, or home screen depending on the device in use.

You can also clear the badge using:

navigator.setAppBadge(0);

///or

navigator.clearAppBadge();

Additionally, you can also use a client badge, which may display a badge in the browser tab or on the page icon:

navigator.setClientBadge(10);

You can also clear a client badge using:

navigator.setClientBadge(0);

///or

navigator.clearClientBadge();

This API becomes even more relevant with the recent support from iOS Safari 16.4 on apps added to the home screen. It can create a native-like experience just like any mobile app. It is used by our own Web SDK to display the unread number of messages.

Conclusion

This is just the tip of iceberg, there are many other APIs that can give your PWA superpowers, and provide a native-like experience for users, with fast performance, offline support, and seamless integration with the device's operating system and hardware.

As always, we hope you liked this article, and if you have anything to add, we are available via our Support Channel.

Keep up-to-date with the latest news