DEV Community

Cover image for 5 web APIs that add mobile functionality to your project
Matt Angelosanto for LogRocket

Posted on • Originally published at blog.logrocket.com

5 web APIs that add mobile functionality to your project

Written by Chimezie Enyinnaya ✏️

As developers, we frequently use APIs (Application Programming Interfaces) to implement complex functionalities easily or create them to abstract complexity. APIs are what allow services to talk to each other and do things like post a Tweet or display a map.

We can classify web APIs into two categories for building client-side web applications:

  • Browser APIs: These are APIs that interface with JavaScript, allowing developers to implement functionalities easily. APIs such as the DOM, Fetch, Audio and Video, WebGL, Notifications and so much more
  • Third-party APIs: You’ve probably used one in your project already. These are APIs that are not built into the browser by default. They're provided by companies such as Google, Facebook, Trello, etc. to allow you to access their functionality via JavaScript and use it on your project

Let's go through some of the popular Web APIs:

  • Geolocation API: This API allows access to retrieve location information of the host device
  • Document Object Model API: The DOM is the API for HTML documents in the sense that it is the interface between your JavaScript program and the HTML document. The DOM itself has an extensive list of interfaces such as the Document interface, Window interface, and so on
  • History API: The History API is abstracted in most of the Router implementations. The API enables you to track and modify the browser's URL and history data, as well as access your browsing history through JavaScript
  • Canvas API: The Canvas API allows you to display different visual graphics on the page by using a <canvas> element, which is useful for HTML games and charts
  • Web Animations API: The Web Animations API enables coordinated visual changes on your page. It combines the pros of CSS transitions/animations and JavaScript-based animations.

In this article, I'll be exploring some of my favorite APIs that provide mobile-friendly functionality. This can include anything from social media shares and clipboard operations to contact, speech, and notifications functionalities.

5 mobile functionality web APIs for your next project

So far, we've discussed some common APIs that you've made use of directly or indirectly through JavaScript libraries.

In this section, we'll explore five unique APIs that you might need for your next project. These APIs are important because they bring mobile native functionalities to the web.

Web Share API

This API helps you implement sharing functionality on your websites. It gives that mobile native-sharing feel. It makes it possible to share text, files, and links to other applications on the device.

The Web Share API is accessible through the navigator.share method:

if (navigator.share) {
  navigator.share({
    title: 'Logrocket alert here',
    text: 'Check out Logrocket',
    url: '<https://logrocket.com/>',
  })
    .then(() => console.log('Successful share'))
    .catch((error) => console.log('Error sharing', error));
}
Enter fullscreen mode Exit fullscreen mode

The code snippet above exemplifies how to share text using vanilla JavaScript. One important thing to take note of is that you can only invoke this action with the onclick event:

function Share({ label, text, title }) {
  const shareDetails = { title, text };

  const handleSharing = async () => {
    if (navigator.share) {
      try {
        await navigator.share(shareDetails).then(() => console.log("Sent"));
      } catch (error) {
        console.log(`Oops! I couldn't share to the world because: ${error}`);
      }
    } else {
      // fallback code
      console.log(
        "Web share is currently not supported on this browser. Please provide a callback"
      );
    }
  };
  return (
    <button onClick={handleSharing}>
      <span>{label}</span>
    </button>
  );
}
Enter fullscreen mode Exit fullscreen mode

The code snippet above is a basic example of how to use the API with React to implement sharing options on your app. You can check out this demo on CodeSandbox.

As of today, Web Share is not supported by the Chrome desktop browser, but it works on the Android browser.

<template>
  <div id="app">
    <div v-if="webShareApiSupported" class="refer-wrapper">
      <p class="refer-text">
        Share your referal code:
        <span class="theCode">{{ referralCode }}</span> with a friend and earn
        when they sign up
      </p>
      <button @click="shareNow">Share</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      referralCode: "Fss4rsc",
    };
  },
  computed: {
    webShareApiSupported() {
      return navigator.share;
    },
  },
  methods: {
    shareNow() {
      navigator.share({
        title: "Refferal Code",
        text: this.referralCode,
      });
    },
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

If you're working with Vue, the code snippet above shows a basic implementation of the Web Share API. Check the full demo.

Contact Picker API

Most mobile apps tend to request access to your contacts or phonebook. This is yet another mobile functionality that's also available on the web.

Let's say you're implementing an airtime recharge feature for a fintech web app. You would want the user to select a contact or multiple contacts. This can be implemented using navigator.contacts. It accepts two arguments: properties, an array containing the property you want to access, and options:

const props = ['name', 'tel',];
const opts = { multiple: true };

async function getContacts() {
  try {
      const contacts = await navigator.contacts.select(props, opts);
      handleResults(contacts);
  } catch (ex) {
      // Handle any errors here.
  }
}
Enter fullscreen mode Exit fullscreen mode

If you're working with React, you can implement the contact picker feature like this:

export default function Contact({ label }) {
  const properties = ["name", "tel"];
  const options = { multiple: true };

  const handleGetContacts = () => {
    try {
      const contacts = navigator.contacts.select(properties, options);
      return contacts;
    } catch (ex) {
      console.log(ex);
    }
  };
  return (
    <>
      <button onClick={handleGetContacts}>
        <span>{label}</span>
      </button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

You can check the React Contact Picker demo on CodeSandbox.

Working with Vue? You're not left out. This is how you could implement this feature with Vue:

<template>
  <div id="app">
    <div v-if="contactApiSupported">
      <div class="contact-wrapper">
        <h4>Select Contacts</h4>
        <button @click="pickContact">Select Contact</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  computed: {
    contactApiSupported() {
      return "contacts" in navigator && "ContactsManager" in window;
    },
  },
  methods: {
    pickContact() {
      const properties = ["name", "tel"];
      const options = { multiple: true };
      try {
        const contacts = navigator.contacts.select(properties, options);
        return contacts;
      } catch (ex) {
        console.log(ex);
      }
    },
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

You can check the Contact Picker demo for Vue on CodeSandbox.

Note that this API will only work on mobile browsers.

Clipboard API

Clipboard operations such as copying, cutting, and pasting are some of the most common features in mobile apps. The Clipboard API enables a web user to access the system clipboard and perform basic clipboard operations.

Previously, you could interact with the system clipboard using the DOM document.execCommand; some libraries still use this method. However, the modern asynchronous Clipboard API provides access to read and write the clipboard contents directly.

Let's see how it works with JavaScript. Reading from the Clipboard:

navigator.clipboard.readText().then(clipText =>
  document.getElementById("outbox").innerText = clipText);
Enter fullscreen mode Exit fullscreen mode

Writing to the Clipboard:

function updateClipboard(newClip) {
  navigator.clipboard.writeText(newClip).then(function() {
    /* clipboard successfully set */
  }, function() {
    /* clipboard write failed */
  });
}
Enter fullscreen mode Exit fullscreen mode

Check out this post if you're trying to implement the Clipboard API with React.

For Vue developers, you can implement the copying text with the API like this:

<template>
  <div id="app">
    <p>Copy this:</p>
    <input v-model="code" />
    <button v-if="supportCBApi" @click="copyMessage">Copy</button>
    <div v-if="message">{{ message }}</div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      message: "",
      code: "FC Barcelona for ever",
      supportCBApi: false,
    };
  },
  created() {
    if (navigator.clipboard) {
      this.supportCBApi = true;
    }
  },
  methods: {
    copyMessage() {
      navigator.clipboard
        .writeText(this.code)
        .then(() => {
          console.log("Text is on the clipboard.");
          this.message = "Code copied to clipboard.";
        })
        .catch((err) => console.error(err));
    },
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

Web Speech API

Most mobile apps nowadays incorporate speech recognition and text-to-speech features to improve accessibility and user experience. The Web Speech API brings these functionalities to the browser. In this article, we'll just discuss the SpeechRecognition interface.

Speech recognition is accessible using the SpeechRecognition interface, and it makes use of the default speech recognition system of the device:

const SpeechRecognition = SpeechRecognition || webkitSpeechRecognition; 
const recognition = new SpeechRecognition(); //new SpeechRecognition object
recognition.continuous = false; 
recognition.lang = 'en-US';
recognition.interimResults = false; 

recognition.onstart = function() {
    console.log("Speak into the microphone");
};

recognition.onspeechend = function() {
    // when user is done speaking
    recognition.stop();
}

// This runs when the speech recognition service returns result
recognition.onresult = function(event) {
    var transcript = event.results[0][0].transcript;
    var confidence = event.results[0][0].confidence;
};

// start recognition
recognition.start();
Enter fullscreen mode Exit fullscreen mode

Source: MDN Speech Recognition

Let's go through the code snippet above.

Firstly, we create a speech recognition object by assigning new SpeechRecognition. The SpeechRecognition object has some properties such as:

  • recognition.continuous: Listens to a single result (word or phrase) when speech recognition starts. If set to true, the speechRecognition service keeps listening unless you stop it
  • recognition.lang: The user's language preference
  • recognition.interimResults: Returns interim results alongside final results when set to true

Also, to get our speech recognition service to work, we need to provide a callback for events such as onstart, onspeechend, and onresult.

  • recognition.onstart: When a user triggers this event, the speech recognition service starts
  • recognition.onspeechend: This stops the speech recognition service from running
  • recognition.onresult: This event is fired once a successful result is received

If you want to implement this in React, go through this tutorial that shows you how to use the React Speech Recognition Hook for voice assistance.

Notification API

The Web Notification API is often interchanged with the Web Push API, but they differ. The goal of the Notification API is to display information to the user while the Push API allows the service worker to handle push messages from the server even when the device is inactive.

This is now widely used by blogs and web applications to notify users when there’s a change or update to a service. One common use case for this API is when your app is a PWA (progressive web application) and you need the user to refresh the browser to get new updates to the app.

To create a notification, JavaScript has a Notification constructor:

const message = 'Refresh to get new features';
var notification = new Notification('Savings PWA app', { body: text });
Enter fullscreen mode Exit fullscreen mode

You can implement this API with your desired web framework.

Web APIs that should have widespread support in the future

So far, we've discussed APIs that bring that native mobile feel to the web. A similarity with all those APIs is that they're widely supported by popular modern browsers.

In this section, I'll highlight three APIs that should have widespread support among browsers in the future.

Screen Wake Lock API

Most apps need access to your device's power status. If you've noticed, mobile apps like YouTube will pause if your screen is locked; some other apps like Spotify will continue playing even if the screen is locked.

On the web, the Screen Wake Lock API allows the developer to control the power state of the device when the web app is running. However, it's not yet supported by Firefox, Safari, and Opera Mini browsers.
Screen Wake Lock API

WebXR Device API

Mixed reality is becoming popular nowadays thanks to the likes of Pokemon Go and Google Translate. The WebXR Device API enables developers to build awesome mixed-reality applications for the web as the range of devices that can support XR keeps on increasing.

Browsers such as Android, Opera, Safari, and Firefox still don't support this API.
WebXR Device API

Web NFC API

On mobile devices, NFC helps users make secure transactions and connect with other devices within a certain radius.

On the web, Web NFC will allow sites the ability to read and write to NFC tags when they are in close proximity to the user. So far, it's only supported by Chrome for Android.
Web NFC API

Conclusion

In this article, we discussed Web APIs that add mobile functionality to your project and some other APIs that should have widespread support in the future.

Building for the web means building for all types of users and devices that have access to a web browser. This is why APIs that mimic mobile functionalities are becoming a must for web developers.


LogRocket: Full visibility into your web apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

Try it for free.

Top comments (0)