Telerik blogs
JavaScriptT2 Light_1200x303

These JavaScript APIs are need-to-know for any new developer, including our friends who are getting started in Angular.

When you start coding, you often rely on libraries you might not need. Worse, you can sometimes reinvent the wheel by coding a specific function yourself while a native API exists. 😳

We are in 2021, and modern browsers are becoming more and more powerful. Every single week, new versions are released with new functionalities to make our lives easier. This is why my goal in this article is to show you some native APIs you should not ignore and give you a framework to keep yourself up to date when new ones are released. 😍

To make things easier to read, every part is organized like this:

  1. Starts with a short summary of the API
  2. Code examples
  3. Concrete examples about real-world use cases
  4. Links if you want to go deeper

If you are ready, let’s get started. πŸ’ͺ😁

1. The Web Storage APIs: LocalStorage and SessionStorage

Summary

The Web Storage API has been designed to provide mechanisms by which browsers can store key/value pairs more intuitively than using cookies. There are two web storage APIs you should know:

  • The sessionStorage
  • The localStorage

You can use the session storage API when you need to save something for the page session’s duration (i.e., until the browser or the tab is closed). This means that everything will be available even if you reload the page. On the contrary, if you close your browser or the tab, the session storage will be flushed, and the data will be lost.

On the other hand, local storage is also used to save something but in a persistent way. This means that the local storage is not flushed when the browser is closed and reopened. The only way to clear the localStorage is to call localStorage.clear().

Code Examples

// Save data to sessionStorage
sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
cont data = sessionStorage.getItem('key');

// Remove saved data from sessionStorage
sessionStorage.removeItem('key');

// Remove all saved data from sessionStorage
sessionStorage.clear();
// Save data to localStorage
localStorage.setItem('key', 'value');

// Get saved data from localStorage
cont data = localStorage.getItem('key');

// Remove saved data from localStorage
localStorage.removeItem('key');

// Remove all saved data from localStorage
localStorage.clear();

Real-world Use Cases

  • Saving authentication tokens once a user is logged in
  • Saving the selected locale for multilingual websites
  • Storing the number of page views for the current session

2. The Fetch API

Summary

When you need to fetch data from a remote API, you can use a library like Axios. While you can set it up in your project, an alternative is to rely on the native Fetch API available in all modern browsers. It will make your code lighter, and you will be able to get started quicker. You can customize almost anything to fit your needs, and I have never been limited by using it in one of my projects. πŸ˜‡

Code Examples

// With a promise
fetch("https://jsonplaceholder.typicode.com/photos")
.then((response) => response.json())
.then((photos) => console.log(photos));

// With async/await
const  response  =  await  fetch("https://jsonplaceholder.typicode.com/photos");
const  photos  =  await response.json();

Note: The promise that fetch() returns will not reject HTTP error status even if the response is an HTTP 404 or 500. Instead, it will typically resolve (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

Real-world Use Cases

  • Fetching any king of data from a remote API like the authenticated user, a list of blog posts, and so on

3. The Clipboard API

Summary

The clipboard API has been released to interact with clipboard commands like cut, copy and paste. It is also able to read and write from the system clipboard. It is available under the navigator variable.

Code Examples

// Copy some text in the clipboard
await navigator.clipboard.writeText("Text to copy");

// Read text inside the clipboard
const  clipText  =  await navigator.clipboard.readText();

// Listen to the copy event
document.addEventListener("copy", async  function () {
// ...
});

// Listen to the paste event
document.addEventListener("paste", async  function () {
// ...
});

Note: If you want to copy or read text with images, use the clipboard navigator.clipboard.write() and navigator.clipboard.read().

Real-world Use Cases

  • Provide a way to quickly copy something on the page by clicking on a button like a code snippet or a summary to tweet

4. The Geolocation API

Summary

The geolocation API has been built to let you access your visitor’s location (when they allow for it, of course). It is available under navigator.geolocation. When you access this variable, the user’s browser will ask for permission for privacy reasons.

Code Examples

// Get the current position
navigator.geolocation.getCurrentPosition(
  function (position) {
    var coordinates = position.coords;
    console.log("Your current position is:");
    console.log(`Latitude : ${coordinates.latitude}`);
    console.log(`Longitude: ${coordinates.longitude}`);
    console.log(`More or less ${coordinates.accuracy} meters.`);
  },
  function (err) {
    console.warn(`ERROR(${err.code}): ${err.message}`);
  }
);

// Will call the first function each time the position of the device changes
const  watchId  = navigator.geolocation.watchPosition(
  function (position) {
    var coordinates = position.coords;
    console.log("Your current position is:");
    console.log(`Latitude : ${coordinates.latitude}`);
    console.log(`Longitude: ${coordinates.longitude}`);
    console.log(`More or less ${coordinates.accuracy} meters.`);
  },
  function (err) {
    console.warn(`ERROR(${err.code}): ${err.message}`);
  }
);

// Used to unregister location/error monitoring handlers previously installed using Geolocation.watchPosition().
navigator.geolocation.clearWatch(watchId);

Real-world Use Cases

  • To plot the user’s location on a map πŸ“
  • To display personalized information relevant to their location like a nearby event or party

5. The Page Visibility API

Summary

Let’s say that you want to check if the page is currently focused before executing something. The Page Visibility API has been designed for this purpose and provides events you can watch to know when a document becomes visible or hidden. This means that when the user minimizes the window or switches to another tab, an event will be sent.

Code Examples

// Using an event listener
document.addEventListener(
	"visibilitychange ",
	function () {
		if (document.hidden) {
			console.log("the document is not visible ");
		} else {
			console.log("the document is visible ");
		}
	}
);

// Another way to proceed
document.onvisibilitychange  =  function () {
	console.log("The page visibility has changed ");
};

Real-world Use Cases

  • Save resources and improve the page performance by avoiding unnecessary tasks when the document is not visible
  • Pause an image carousel and prevent it from advancing to the next slide unless the user views the page
  • Avoid pulling data from an API unless the page is focused

6. The Resize Observer API

Summary

The Resize Observer API lets you know when the dimensions of an element change. In a nutshell, it can be handy to trigger a specific function when the user resizes the browser window.

Code Examples

// Will be called when the element(s) is/are resized
var observer =  new  ResizeObserver((entries) => {
	for (let entry of entries) {
		const  content  = entry.contentRect;
		console.log("Element: ", entry.target);
		console.log(`Element size: ${content.width}px x ${content.height}px`);
		console.log(`Element padding: ${content.top}px ; ${content.left}px`);
	}
});

// Observe one or multiple elements
observer.observe(".some-elements ");

// Unobserve one or multiple elements
observer.unobserve(".some-elements ");

// Unobserves all observed element for this observer
observer.disconnect();

Real-world Use Cases

  • Reduce or increase the font size depending on the element’s dimensions

7. The URL API

Summary

This native API has been designed to provide an easy way to parse, construct, normalize and encode URLs. As you will see, it can be handy when you want to get the host or the protocol for a given URL. πŸ˜ƒ

Code Examples

const  url  =  new  URL("http://www.example.com/something?hello=hey#myhash ");

console.log(url.hash); // #myhash
console.log(url.host); // www.example.com
console.log(url.hostname); // www.example.com
console.log(url.href); // http://www.example.com/something?hello=hey#myhash
console.log(url.origin); // http://www.example.com
console.log(url.pathname); // /something
console.log(url.protocol); // http:
console.log(url.search); // ?hello=hey

url.toString(); // It is an alias for URL.href but it can't be used to modify the value.

Real-world Use Cases

  • Parse a URL to extract the domain name
  • Update a given URL by adding search params to it

8. The Vibration API

Summary

The vibration API has been designed to provide physical feedback by shaking the user’s device. If the hardware does not offer vibration (like a desktop computer), the code will do nothing.

Code Examples

// Vibrates for 200ms
window.navigator.vibrate(200);

// Vibrates for 200ms, pauses for 100ms and vibrate for 200ms.
window.navigator.vibrate([200, 100, 200]);

// Cancel all vibrations
window.navigator.vibrate(0);

Real-world Use Cases

  • Vibrate the hardware when the user does a specific action in the interface
  • Notify the user that something significant happened πŸ“±

9. The FullScreen API

Summary

The Fullscreen API has been designed to allow visitors to enter/exit a given element into full-screen.

Code Examples

// Focus the element into full-screen mode
const  element  = document.querySelector(".element-to-focus ");
element.requestFullscreen();

// Exit full screen
await document.exitFullscreen();

// Fires when a document goes in or out of the fullscreen mode
document.onfullscreenchange  =  function (event) {
	console.log("Full screen changed ");
};

// Fires when it fails to transition into full-screen mode
document.onfullscreenerror  =  function (event) {
	console.log("Full screen error ");
};

Real-world Use Cases

  • Allow visitors to focus their browser’s window on a specific element, such as an online game πŸ‘Ύ
  • Focus on a specific part of an analytics dashboard

10. The Lazyload API

Summary

This one is not controlled with JavaScript but with an HTML5 tag. I added it to the list to show you that new handy attributes are being released.

If you need to lazy-load your images or your iframes for performance reasons, there is no need to use a JavaScript API anymore. You can use the loading attribute and set it to lazy.

Code Examples

<img  src="image.jpg "  loading="lazy ">
<iframe  src="myiframe.html "  loading="lazy "></iframe>

Real-world Use Cases

  • Increase the page load by requesting the right resources and defer the other ones when needed πŸ“ˆ

11. Where to Go From There?

As I said earlier, there are a lot of new features released in browsers these days. If you want to stay up to date with the web’s future, I suggest you visit these two unique links on a weekly/monthly basis. πŸ’«

One last word: When you need to check if a specific browser supports a particular feature, go to CanIUse.com. πŸ˜πŸ‘Œ


I hope that, with this article, you can better grasp how powerful native APIs can be to simplify your code and make your apps lighter. I am also always happy to read your comments and your Twitter messages @RifkiNada.

And in case you are curious about my work, you can have a look at it here NadaRifki.com. 😜


author-photo_nada-rifki
About the Author

Nada Rifki

Nada is a JavaScript developer who likes to play with UI components to create interfaces with great UX. She specializes in Vue/Nuxt, and loves sharing anything and everything that could help her fellow frontend web developers. Nada also dabbles in digital marketing, dance and Chinese. You can reach her on Twitter @RifkiNadaor come on her website, nadarifki.com.

Related Posts

Comments

Comments are disabled in preview mode.