DEV Community

Cover image for 5 Javascript web APIs
Kamran Ahmad
Kamran Ahmad

Posted on

5 Javascript web APIs

  1. Clipboard API : Allows Copying comtent to and reading content from the device clipboard
navigator.clipboard.writeText('hello')
.then(() => { /* success */}

navigator.clipboard.readText()
.then(text => { /* success */}
Enter fullscreen mode Exit fullscreen mode
  1. Media Capture : The Media Capture API is a Web API that allows web applications to access media capture devices like cameras and microphones, enabling them to capture media directly from the user's device. This API simplifies the process of capturing media, such as photos, videos, and audio recordings, without the need for plugins or additional software.

The Media Capture API provides two main interfaces:

MediaDevices: This interface provides access to media input devices like cameras and microphones and allows you to obtain media streams from them.

MediaStream: This interface represents a stream of media content, such as video or audio, obtained from media devices.

Here's an example of how to use the Media Capture API to capture a photo from the user's camera and display it on a web page:


<!DOCTYPE html>
<html>
<head>
  <title>Media Capture API Example</title>
</head>
<body>
  <h1>Photo Capture</h1>
  <video id="videoElement" width="400" height="300" autoplay></video>
  <button id="captureButton">Capture Photo</button>
  <canvas id="canvasElement" width="400" height="300"></canvas>
  <img id="photoElement" src="#" alt="Captured Photo">

  <script>
    const videoElement = document.getElementById('videoElement');
    const captureButton = document.getElementById('captureButton');
    const canvasElement = document.getElementById('canvasElement');
    const photoElement = document.getElementById('photoElement');

    async function setupMediaStream() {
      try {
        const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true });
        videoElement.srcObject = mediaStream;
      } catch (error) {
        console.error('Error accessing media devices:', error);
      }
    }

    captureButton.addEventListener('click', () => {
      const context = canvasElement.getContext('2d');
      context.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
      const capturedPhotoURL = canvasElement.toDataURL('image/png');
      photoElement.src = capturedPhotoURL;
    });

    // Call the setupMediaStream function on page load
    document.addEventListener('DOMContentLoaded', setupMediaStream);
  </script>
</body>
</html>


Enter fullscreen mode Exit fullscreen mode
  1. Animations API : he Animation API in JavaScript allows you to create and manage animations using the requestAnimationFrame method and the Animation interface. This API provides a more efficient and smoother way to create animations compared to using traditional timers like setInterval or setTimeout.

Here's a simple example of how to use the Animation API to create a basic animation:

<!DOCTYPE html>
<html>
<head>
  <title>Animation API Example</title>
  <style>
    #box {
      width: 50px;
      height: 50px;
      background-color: red;
      position: absolute;
    }
  </style>
</head>
<body>
  <div id="box"></div>
  <script>
    const box = document.getElementById('box');

    function animateBox(timestamp) {
      const startPosition = 0; // Start position (left)
      const endPosition = 200; // End position (left)
      const duration = 2000; // Animation duration in milliseconds (2 seconds)
      const startTime = timestamp || performance.now();
      const progress = Math.min((timestamp - startTime) / duration, 1);
      const newPosition = startPosition + (endPosition - startPosition) * progress;

      box.style.left = newPosition + 'px';

      if (progress < 1) {
        // Continue the animation
        requestAnimationFrame(animateBox);
      }
    }

    // Start the animation on button click
    document.addEventListener('DOMContentLoaded', () => {
      document.addEventListener('click', () => {
        requestAnimationFrame(animateBox);
      });
    });
  </script>
</body>
</html>


Enter fullscreen mode Exit fullscreen mode
  1. Share API : The Share API is a Web API that allows web applications to invoke native sharing capabilities of the underlying platform. With this API, you can easily share content such as text, URLs, and files to other applications on the user's device, like social media apps, messaging apps, or email clients. This simplifies the process of sharing content from a web page without the need for custom sharing functionality.

Here's an example of how to use the Share API:


<!DOCTYPE html>
<html>
<head>
  <title>Share API Example</title>
</head>
<body>
  <h1>Share Something</h1>
  <button id="shareButton">Share Content</button>

  <script>
    const shareButton = document.getElementById('shareButton');

    shareButton.addEventListener('click', async () => {
      if (navigator.share) {
        try {
          await navigator.share({
            title: 'Check out this cool website!',
            text: 'I found this awesome website with great content!',
            url: 'https://www.example.com',
          });
          console.log('Content shared successfully.');
        } catch (error) {
          console.error('Error sharing content:', error);
        }
      } else {
        console.log('Sharing not supported on this platform.');
      }
    });
  </script>
</body>
</html>


Enter fullscreen mode Exit fullscreen mode
  1. Web Storage API: The Web Storage API allows you to store data on the client-side, persisting even after the browser is closed.
<!DOCTYPE html>
<html>
<head>
  <title>Web Storage API Example</title>
</head>
<body>
  <input type="text" id="inputText" placeholder="Enter some text">
  <button id="saveButton">Save</button>
  <div id="output"></div>
  <script>
    // Example: Save data to local storage and retrieve it
    const inputText = document.getElementById('inputText');
    const saveButton = document.getElementById('saveButton');
    const outputDiv = document.getElementById('output');

    saveButton.addEventListener('click', () => {
      const userInput = inputText.value;
      localStorage.setItem('userInputData', userInput);
      outputDiv.textContent = `Saved: ${userInput}`;
    });

    // Retrieve data on page load
    const savedData = localStorage.getItem('userInputData');
    if (savedData) {
      outputDiv.textContent = `Saved: ${savedData}`;
    }
  </script>
</body>
</html>


Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
sfundomhlungu profile image
sk

I didn't know about the Share API, so cool!!, let me play with it 🚀

Collapse
 
ikamran01 profile image
Kamran Ahmad

that so cool let me know how enjoy that share api