avatarArman Murzabulatov

Summary

This article provides an overview of six browser APIs that can be used in Angular to create dynamic and interactive web applications.

Abstract

The article begins by introducing the concept of browser APIs, which are a suite of interfaces offered by browsers, including the Document Object Model (DOM) API, Fetch API, Web Storage API, and others. The article then discusses best practices for using these APIs, such as checking compatibility, asking for permissions, considering performance, and prioritizing security.

The article then goes on to describe six browser APIs in detail:

  1. Document Object Model (DOM) API: This API provides methods to create, read, update, and delete nodes in the DOM. While Angular offers ways to interact with the DOM via its template and component system, there may be rare cases where direct interaction with the DOM is necessary.
  2. Fetch API: This API provides a way to make network requests, making it essential for fetching data, sending data, and other tasks. While it is still possible to use the native Fetch API, it is strongly advised to use Angular’s own HTTP client.
  3. Web Storage API: This API provides mechanisms to store key-value pairs in a web browser. Angular does not provide a built-in service for web storage, so developers must interact with the browser’s API directly.
  4. Handling Browser Events: While Angular provides ways to handle user events like clicks or inputs, developers can also listen to events directly.
  5. Geolocation API: This API allows users to share their location with trusted web apps. The article provides a step-by-step guide for using the Geolocation API in an Angular application.
  6. Notification API: This API lets web applications display notifications to users. The article provides a step-by-step guide for using the Notification API in an Angular application.

The article concludes by discussing the importance of safeguarding against platform-specific code and lists upcoming topics for further exploration.

Bullet points

  • Browser APIs are a suite of interfaces offered by browsers, including the Document Object Model (DOM) API, Fetch API, Web Storage API, and others.
  • Best practices for using browser APIs include checking compatibility, asking for permissions, considering performance, and prioritizing security.
  • The Document Object Model (DOM) API provides methods to create, read, update, and delete nodes in the DOM.
  • The Fetch API provides a way to make network requests, making it essential for fetching data, sending data, and other tasks.
  • Angular does not provide a built-in service for web storage, so developers must interact with the browser’s API directly.
  • While Angular provides ways to handle user events like clicks or inputs, developers can also listen to events directly.
  • The Geolocation API allows users to share their location with trusted web apps.
  • The Notification API lets web applications display notifications to users.
  • It is important to safeguard against platform-specific code when interacting with the browser’s API.
  • Upcoming topics for further exploration include the File API, WebRTC, Canvas, and WebGL.

6 Browser APIs to use in Angular

Image generated with Midjourney and edited further by the author

Hey there! 🌟 Ever wondered how to make your Angular apps more lively and engaging by tapping into the capabilities of your user’s browser?

In the ever-evolving landscape of web development, modern browsers present a wealth of APIs. These APIs pave the way for creating dynamic, interactive web applications that mirror native app experiences. As you navigate this space, Angular emerges as an invaluable ally. Although Angular simplifies many processes with its robust features, there are instances where direct interaction with the browser’s APIs is essential. Here, we’ll unravel the intricacies of leveraging core browser APIs within an Angular application.

Grab a cup of your favorite beverage, and let’s dive in!

What is the Browser’s API?

When we talk about the “browser’s API”, we refer to a suite of interfaces the browser offers, including:

  • Document Object Model (DOM) API
  • Fetch API for network requests
  • Geolocation API for location details
  • Web Storage API (localStorage & sessionStorage)

… and the list goes on.

Before we start

Before we jump into the diverse world of browser’s APIs, it’s important to keep in mind a few good practices that are common for most of them.

  1. Check Compatibility: Not all APIs are available in all browsers. Use resources like Can I use to check compatibility.
  2. Ask for Permissions: For APIs that require user permissions, like Geolocation or Notifications, always ask the user explicitly and handle denials gracefully.
  3. Performance Considerations: Some APIs can be resource-intensive. Always consider the impact on performance and user experience.
  4. Security: Only request data you need, and always use HTTPS, especially when dealing with sensitive APIs.

Now are are good to start …

1. Document Object Model (DOM) API

The DOM is a tree-like representation of a webpage. The DOM API provides methods to create, read, update, and delete its nodes.

In the old Vanilla Javascript world we used to interact with it all the time like:

  • Accessing an element: document.getElementById('id').
  • Changing text content: element.textContent = 'New Content'.
  • Adding classes: element.classList.add('new-class').

But nowadays with the popularity of front-end frameworks and libraries, we rarely directly interact with the DOM.

Although Angular offers ways to interact with the DOM via its template and component system, sometimes (in very rare cases) you may need to access the DOM directly. To do that you have to utilise Renderer2:

Here, ElementRef provides direct access to the host DOM element, while Renderer2 abstracts away direct DOM manipulations to ensure the app remains platform-agnostic.

However, direct DOM manipulations are often discouraged in Angular. Instead, use Angular’s templating system or Renderer2 whenever possible.

2. Fetch API

The Fetch API provides a way to make network requests, making it essential for fetching data, sending data, and other tasks.

Although it is still possible to use native Fetch API, it is strongly advised to use Angular’s own HTTP client.

3. Web Storage API

Angular does not provide a built-in service for web storage, so you’d interact with the browser’s API directly.

This API provides mechanisms to store key-value pairs in a web browser. It includes two storage mechanisms:

  • localStorage: Persists even when the browser is closed.
  • sessionStorage: Cleared when the page session ends.

Example usage of local storage:

To make it more Angular-friendly, consider wrapping these operations inside an injectable service.

4. Handling Browser Events

While Angular provides ways to handle user events like clicks or inputs, you can also listen to events directly:

5. Geolocation API

The Geolocation API allows users to share their location with trusted web apps.

Basic vanilla JS example:

To use the browser’s Geolocation API in an Angular application, you can follow these steps:

Permission Request: First, ensure your website is served over HTTPS. This is required because most browsers only allow access to the Geolocation API on secure origins.

Step 1: Update Angular App Permissions: In your src/polyfills.ts file, add the following:

Step 2: Service Creation: Create a service to encapsulate the geolocation functionality.

ng generate service geolocation

Step 3: Modify the GeolocationService:

Inside the geolocation.service.ts file, you can create methods to fetch the location.

Step 4: Usage in Component:

You can now use the GeolocationService in any Angular component:

Error Handling: Remember to handle errors appropriately. Users can deny access to their location, so it’s a good practice to provide feedback or alternative actions in those cases.

Consider Using Libraries: If you plan to do more with geolocation, like watching the location or integrating with maps, consider using libraries like @angular/google-maps for advanced functionalities.

Remember that the Geolocation API is asynchronous and depends on the user granting permissions. Always design with the user’s privacy in mind and inform them why you need their location.

6. Notification API

This API lets web applications display notifications to users.

Usage in vanilla JS:

Using the Browser’s Notification API from an Angular application involves several steps:

Step 1: Check for Browser Support: Before using the Notification API, you should check whether the user’s browser supports notifications. You can check if the browser supports notifications with:

Step 2: Requesting Permission: To show notifications, you must request and obtain permission from the user. There are three possible states for notification permissions: default, granted, and denied. You can request permission from the user like this:

Step 3: Displaying the Notification: Once permission is granted, you can use the API to display notifications. Once permission has been granted, you can display a notification:

Using in Angular:

You can wrap the above logic in an Angular service for better structure and reusability:

Now, you can inject this service wherever you need it and use it to show notifications:

Note: Ensure that you have imported and added the service to the providers array in your module or provided it in root as shown in the example.

Also, bear in mind that there are further nuances to consider, like handling situations when the page is not visible, integrating with service workers, etc., depending on your use-case. Always refer to the latest specification/documentation for the Notification API and be aware of different browser implementations and compatibility issues.

Safeguarding against Platform Specific Code

When interacting with the browser’s API, ensure your code remains platform-agnostic. Remember, Angular can also run on other platforms like server-side (with Angular Universal) or within Web Workers. You can use Angular’s isPlatformBrowser function to conditionally run browser-specific code:

Coming Up Next…

We’ve barely scratched the surface! Upcoming topics will delve into more advanced browser APIs, such as:

  • File API: provides functionalities to read and manipulate file content
  • WebRTC (Real-Time Communication): direct peer-to-peer communication, enabling real-time video, audio, and data sharing
  • Canvas and WebGL: for creating 2D and 3D graphics and animations in the browser
  • etc

If you’re keen, make sure to follow and stay tuned for these explorations! Your feedback, through claps 👏 or comments 💬, is always welcome and appreciated.

Closing Notes 📝

The modern browser is a goldmine of features for developers. By adeptly using these APIs in our Angular applications, we can craft richer, more interactive experiences for our users. However, it’s crucial always to prioritize security, user privacy, and overall experience. Happy coding, and till next time! 🚀👨‍💻👩‍💻

Browsers
Angular
Web Development
Programming
JavaScript
Recommended from ReadMedium