Hrithwik Bharadwaj

Hrithwik Bharadwaj

5 Web API's for your Next Project

5 Web API's for your Next Project

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

There are a few amazing web API's supported by modern browsers and these are few you might want to use in your next project.

Do note that some browsers might not support all these API's

Clipboard API ๐Ÿ“‹

Implementing clipboard functionality is even simpler now with the clipboard API.

Using Clipboard API ,You can either Copy or Paste from your Clipboard

Here is how to copy

const text = "Some Information"
if (!navigator.clipboard) {
    // Clipboard API not available
    return
  }

 try {
    await navigator.clipboard.writeText(text)
    // copies to clipboard
  } catch (err) {
    console.error('Failed to copy!', err)
  }

Here is how to Paste from the user's clipboard


if (!navigator.clipboard) {
    // Clipboard API not available
    return
  }

 try {
    const text = await navigator.clipboard.readText()
    // copies info from clipboard to text variable
  } catch (err) {
    console.error('Failed to copy!', err)
  }

Share Target API ๐Ÿ”—

Let's say you have built a PWA where people upload photos or share links and allowing users to see your app while clicking on the share button makes your PWA look dope.

ezgif.com-video-to-gif.gif

Add this in your mainfest.json file. If you don't know about manifest json file or PWA's in general .Check out my article on Converting your website into PWA

Manifest.json

"share_target": {
  "action": "/share-target/",
  "method": "GET",
  "params": {
      "text": "link",
 }
}

Now on the app side, you can get the data that the user has shared through a query parameter called link

The above code works only for links or text but what if you have to share images or files?

To implement for images/files checkout an article at web.dev here

File System API

Let's say you want a user to upload a file and the below code works for reading the file

<input type="file">

and you can save the file using download inside an anchor tag

<a href="" download="file.txt > Save File </a>

But you can't just edit the file which you have accessed from the above method. With File Share API you can edit the files you have read and save them which sends a new prompt to the user.

Do note that this is a new feature and only chrome 86 or greater supports this.

index.html

<button id="fs-open"> Upload File </button>

index.js

const getFile = document.getElementById('fs-open')

getFile.onClick = async() =>{
[fileHandle] = await window.showOpenFilePicker();
if (fileHandle.type === 'file') {
          const fileData = await fileHandle.getFile();
}
else if(fileHandle.type==='directory'){
          const dirName = 'directoryToGetName';

           // assuming we have a directory handle: 'currentDirHandle'
          const subDir = currentDirHandle.getDirectoryHandle(dirName, {create: true});
}

};

To save a file to disk, you can either use that filehandle that you got earlier or call showSaveFilePicker() to get a new filehandle.


async function saveFile(fileHandle) {
  if (!fileHandle) {
    fileHandle = await window.showSaveFilePicker();
  }
  const writable = await fileHandle.createWritable();
  await writable.write(contents);
  await writable.close();
}

You can even get directories and create files in the directories.

This is especially useful if you want to create Notepad Applications on the web. Read more about it here .

Web Storage API

Local Storage is great for storing information that shouldn't be sent to the server, it also doesn't have any expiration, and also it has more storage capacity on the other hand session storage can be used for a session and for a fixed amount of time.

Here is how to store let's say a username

localStorage.username= 'hrithwik'

now let's say you have to retrieve the username of the username without a further API call

let username = localStorage.username

Remember I told you that there is no expiration for this?

localStorage.removeItem('username')

User Media API

Let's say you are building the next zoom or an AR app. How do you access the camera ?

That can be done using navigator api


navigator.mediaDevices.getUserMedia({
  video: true,
  audio: true
})
// get's both audio and video from the user

This returns a promise and can be stored in a variable. Let's Display the stream on the browser now

<button id="video-on">Get access to camera</button> <video autoplay></video>
document
  .querySelector('#video-on')
  .addEventListener('click', async function init(e) {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: true
        audio:true
      })
      document.querySelector('video').srcObject = stream
      document.querySelector('#video-on').setAttribute('hidden', true)
      setTimeout(() => {
        track.stop()
      }, 3 * 1000)
    } catch (error) {
      alert(`${error.name}`)
      console.error(error)
    }
  })

This hides the button after clicked and shows the video on the browser.

Bonus - Geo Location API

What if you are building an app that requires constant GPS Information from the users' device.

That's where GeoLocation API comes in. It gives you not only information regarding the longitude and latitude of users but also access to other various sensors which can be workaround with more use cases.

 if(!navigator.geolocation) {
    status.textContent = 'Geolocation is not supported by your browser';
  } else {
    status.textContent = 'Locatingโ€ฆ';
    navigator.geolocation.getCurrentPosition(success, error);
  }

function sucess(position){
const latitude  = position.coords.latitude;
const longitude = position.coords.longitude;
mapLink = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
}

function error(){
 status.textContent = 'Unable to retrieve your location';
}

You can even see if the device is in motion by adding a event listner.

window.addEventListner('devicemotion',(event) =>{
console.log(event)
}

If you want to discover more Web API's Here is a list of all Web API's

If you are on Hashnode and seeing this. Consider following my blog :)

Also, I love Filter Coffee

Interested in reading more such articles from Hrithwik Bharadwaj?

Support the author by donating an amount of your choice.

Recent sponsors
ย 
Share this
Proudly part of