Browser Storage

Use browser features such as localStorage, sessionStorage, and Web APIs.

Modern websites often need to remember information about users and access features provided by the browser. JavaScript can accomplish these tasks using Browser Storage and Web APIs.

Browser Storage allows websites to store data directly in the user's browser, while Web APIs provide access to browser features and device capabilities.

What Is Browser Storage?

Browser Storage allows websites to save data locally on a user's device.

  • Local Storage
  • Session Storage
  • Cookies

Local Storage

Local Storage stores data permanently until it is manually removed.

Saving Data

javascript
localStorage.setItem("theme", "dark");

Reading Data

javascript
let theme = localStorage.getItem("theme");

console.log(theme);

Output:

javascript
dark

Session Storage

Session Storage is removed when the browser tab is closed.

javascript
sessionStorage.setItem("username", "John");

console.log(sessionStorage.getItem("username"));

Output:

javascript
John

Cookies

Cookies are small pieces of data often used for authentication and user tracking.

javascript
document.cookie = "username=John";

Many websites use cookies to keep users logged in between visits.

What Are Web APIs?

Web APIs are browser features that JavaScript can use.

  • Geolocation API
  • Clipboard API
  • Notifications API
  • Fetch API
  • Web Storage API

Geolocation API

javascript
navigator.geolocation.getCurrentPosition(
    position => {
        console.log(position.coords.latitude);
        console.log(position.coords.longitude);
    }
);

This is commonly used in map applications and delivery services.

Clipboard API

javascript
navigator.clipboard.writeText("Hello World");

This feature is useful for copy buttons and sharing links.

Notifications API

javascript
new Notification("New Message Received");

Notification permissions must be granted by the user before they can be displayed.

Real-World Example

  • Local Storage saves products added to the cart.
  • Cookies keep users logged in.
  • Geolocation detects delivery locations.
  • Clipboard API copies discount codes.
  • Notifications alert users about order updates.

Security Considerations

Sensitive information such as passwords should never be stored directly in Local Storage or Session Storage.

Summary

Browser Storage and Web APIs allow JavaScript applications to store data and interact with browser features. Local Storage, Session Storage, Cookies, Geolocation, Clipboard, and Notifications are essential for modern interactive web applications.

Let's learn with DevBrainBox AI