Share 7 JavaScript Web APIs that you may not have used

ab5cd3c862e1b9ee735b5905a43f8b5f.jpeg

JavaScript is the super programming language to the rescue when it comes to building websites and web applications. It has many amazing and useful features that we can use to make the web more interactive. Amongst the power of JavaScript, there is Web API that makes web development much easier.

You can think of the Web API as the magical conduit that enables JavaScript to interact with the web browser and access all kinds of cool functionality.

For example, they give you the ability to play audio and video, get the user's location, store data locally, and even send notifications to the user's device. These are just some examples, much more can be achieved using JavaScript's Web API. So, in this article, we'll explore some extremely useful and powerful JavaScript Web APIs that you can use in your code.

Whether you're a beginner or an experienced developer, we've made sure this article helps you sharpen your skills and create impressive web experiences. let's start!

1. Select the API

Did you know that you can easily get selected text on a web page? When the user selects or highlights text with the mouse, you can use JavaScript's selection API to retrieve that text.

We can access this API in JavaScript through the window object. You can take a look at the code sample below:

const getSelection = window.getSelection();
if (selection.rangeCount > 0) {
  const range = selection.getRangeAt(0);
  const selectedText = range.toString();
  console.log('Selected Text:', selectedText);
}

f5280a2f7becc4e448d864a0dd10167f.jpeg

Therefore, the selection API is a great way to manipulate and obtain information about user text selections in web pages.

By using this useful API in JavaScript, you can perform various operations on user-selected text, such as modifying content, applying formatting, or extracting information for further processing in your web application.

2. Full screen Web API

The fullscreen API is useful in JavaScript when we want an element in a webpage to go into fullscreen mode. Therefore, this API allows us to switch a web page or element to full screen mode, providing a better experience for the user. To start using the fullscreen API, we use the requestFullScreen() method on the element or page to which fullscreen is to be applied. Here is a code example of how to use the API:

const element = document.getElementById('myElement'); //select the element!

// Check if fullscreen mode is supported
if (element.requestFullscreen) {
  // Enter fullscreen mode
  element.requestFullscreen()
    .then(() => {
      // Fullscreen mode entered successfully
      console.log('Entered fullscreen mode');
    })
    .catch((error) => {
      // Fullscreen mode failed to enter
      console.error('Error entering fullscreen mode:', error);
    });
} else {
  // Fullscreen mode is not supported
  console.log('Fullscreen mode is not supported');
}

// Exit fullscreen mode
function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen()
      .then(() => {
        console.log('Exited fullscreen mode');
      })
      .catch((error) => {
        console.error('Error exiting fullscreen mode:', error);
      });
  }
}

As you can read, we use document.getElementById() to select the element on the page that we want to make full screen.

After that, we check if the requestFullscreen method is available on the element. If available, we call element.requestFullscreen() to enter fullscreen mode. The returned Promise resolves on successful entry to fullscreen mode and rejects on error.

We then handle the case where fullscreen mode is not supported by checking if requestFullscreen is available.

Finally, we define a function called exitFullscreen() that can be used to exit fullscreen mode using document.exitFullscreen().

3. Clipboard API

If you want users to be able to easily copy and paste text, then the clipboard API should be used in your code.

This JavaScript API allows us to interact with the user's clipboard, enabling copy and paste functionality in a website or web application.

Here's a code sample using the Clipboard API in JavaScript:

// Copy text to clipboard
navigator.clipboard.writeText('Hello JavaScript!')
  .then(() => {
    console.log('Text copied to clipboard.');
  })
  .catch((error) => {
    console.error('Failed to copy text: ', error);
  });

As you can see, the method writeText() allows us to add text to the clipboard, enabling a convenient copy-paste functionality on your website.

You can also read text from the clipboard by simply using:

const getText = await navigator.clipboard.readText();

4. Geolocation API

The Geolocation API in JavaScript allows you to easily get the user's geographic location information. This is useful for providing location-based services on your website.

See the code sample below for how to use the Geolocation API in JavaScript:

// Get user's current position
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition((position) => {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
  }, (error) => {
    console.error('Error getting location: ', error);
  });
}

In the code above, we check whether the geolocation property exists in the navigator object to determine whether the browser supports geolocation functionality. If the geolocation function is supported, we call the getCurrentPosition() method to obtain the current position of the device.

The getCurrentPosition() method accepts two callback functions as parameters: the first callback function is called when the position is successfully obtained, and the second callback function is called when an error occurs.

We then access the longitude and latitude coordinates from the coords property of the position object and log them to the console.

Next, in the error callback function, we handle any errors that occur while retrieving the geolocation and log the error messages to the console.

Therefore, the geolocation API is useful in many scenarios, such as serving location-based content or displaying the user's location on a map.

5. Vibration API

The vibration API in JavaScript allows us to trigger the vibration function of the device to get feedback and improve user experience.

Through this Web API, you can easily make the device vibrate, which is often used to vibrate mobile devices.

Here is a code example:

// Vibrate device for 1000 milliseconds
navigator.vibrate(1000);

So the code above allows you to vibrate the device for 1 second.

6. Detect network bandwidth

Bandwidth refers to the amount of data transferred over an internet connection within a specific time frame.

In JavaScript, the navigator object provides an easy way to detect and evaluate network bandwidth. Here is a code example:

navigator.connection.downlink;

You can try pasting this code into your browser console and you will get something like this:

51d3ac0ac264ebc07a67361b328754c7.jpeg

Using the navigator object, we access the downlink property to determine the speed of the Internet connection in megabits per second (Mbps).

In testing, I got a result with a value of 5.65. However, your results may vary depending on your internet speed and the browser you are using. You can experiment on your own by visiting your browser console.

7. Speech Recognition API

The Speech Recognition API in JavaScript allows web applications to integrate speech recognition and synthesis. Here's an example of how to use the Web Speech API:

Speech recognition (speech-to-text):

// Request speech recognition
const recognition = new window.SpeechRecognition();

// Start speech recognition
recognition.start();

// Handle recognition results
recognition.onresult = (event) => {
  const transcript = event.results[0][0].transcript;
  console.log('Speech Recognition Result:', transcript);
};

// Handle recognition errors
recognition.onerror = (event) => {
  console.error('Speech Recognition Error:', event.error);
};

Speech synthesis (text-to-speech):

// Create speech synthesis utterance
const utterance = new SpeechSynthesisUtterance();
utterance.text = 'Hello, world!';

// Speech synthesis voices
const voices = speechSynthesis.getVoices();

// Set voice and language
utterance.voice = voices.find(voice => voice.lang === 'en-US');

// Speak the text
speechSynthesis.speak(utterance);

Speech Recognition:

  • We create a new instance of SpeechRecognition.

  • We start speech recognition with recognition.start().

  • When a recognition result is available, the onresult event is triggered.

  • We get the text of the recognized speech from event.results and log it to the console.

  • If an error occurs during speech recognition, the onerror event will be triggered and the error will be logged to the console.

speech synthesis:

  • We create a new instance of SpeechSynthesisUtterance and set the text to be converted to speech.

  • We use speechSynthesis.getVoices() to get the available speech synthesis voices.

  • We set the desired voice and language by filtering the available voices against the desired language code.

  • Finally, we use speechSynthesis.speak(utterance) to play the spoken text with the selected sound.

It's important to note that browser support for the Web Speech API may vary, and speech recognition and synthesis features may require user consent and permissions.

Summarize

As you can see above, these APIs are rarely used by developers, but they can add unique and powerful features to your website. Also, make sure to check each API for browser compatibility, and consider providing fallbacks for unsupported browsers.

Due to the limited space of the article, today’s content will be shared here. At the end of the article, I would like to remind you that the creation of articles is not easy. If you like my sharing, please don’t forget to like and forward it, so that more people in need See. At the same time, if you want to gain more knowledge of front-end technology, welcome to follow me, your support will be the biggest motivation for me to share. I will continue to output more content, so stay tuned.

Original:
https://javascript.plainenglish.io/7-useful-javascript-web-apis-that-you-probably-dont-know-b766c613bab4

By Mehdi Aoussiad

Indirect translation, some self-adapted and added parts, the translation level is limited, it is inevitable that there are omissions, welcome to correct

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/131335685