PWA vibration API

Let's use the navigator to shake your device

Brm, Brm!

Interaction with the user on a "sensual" level can greatly improve the user experience of your app. Typically, we as devs have to limit ourselves to fancy animations, such as parallax effects or 3D-renders to convey a more realistic feeling inside our apps. But did you know that Progressive Web Apps can deliver so much more? Today we'll take a look at the haptic side of interactions between the web and the user.

Rumble in the (dev-)jungle

As of writing, not all environments provide support for the new Vibration-API. Specifically, every Chromium and Firefox-browser can be used, whereas every variant of Safari/WebKit has no support. Note: every browser on iOS uses WebKit as its engine.

The usage of the API itself is as straightforward as it gets. Here's an example:

// All examples assume that we have 
// access to the 'window' and use Typescript.
// Specifically, we're using optional chaining
// for simplified handling of undefined if no
// API is available.

const vibrateOnceOnClick = () => {
  // A simple one-liner is all that's needed.
  // To use a single vibration, we simple 
  // provide an integer representing the ms
  // a single pulse should last.

const vibratePatternOnClick = () => {
  // For more than one puse, an array has to be
  // provided, again defining each pulse's lenght
  // in milliseconds.
  window.navigator?.vibrate?.([50, 200, 50, 200]);

To proof that this code is working, simply tap the copy-button in bottom right corner of the code snippet. If your device supports it, then a gentle vibration should be started to acknowledge the copy-to-clipboard action.

We're almost done, let's just take a look at the last features of the API:

const cancelVibration = () => {
  // Quick and easy: call 'vibrate' with
  // a val of 0 and the current vibration
  // is stopped.

And that's about it! Not much to cover, but applied correctly, i.e. not too much in your app and only when it's applicable, the vibration-API is a really great feature to use. I think the best use case is to haptically confirm or deny important actions the user has made, e.g. the copy-action for code in this case or a permanent delete-action in another app.

  • Tom