JavaScript 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
localStorage.setItem("theme", "dark");Reading Data
let theme = localStorage.getItem("theme");
console.log(theme);Output:
darkSession Storage
Session Storage is removed when the browser tab is closed.
sessionStorage.setItem("username", "John");
console.log(sessionStorage.getItem("username"));Output:
JohnCookies
Cookies are small pieces of data often used for authentication and user tracking.
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
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
navigator.clipboard.writeText("Hello World");This feature is useful for copy buttons and sharing links.
Notifications API
new Notification("New Message Received");Notification permissions must be granted by the user before they can be displayed.
Security Considerations
Sensitive information such as passwords should never be stored directly in Local Storage or Session Storage.
Key Takeaways
- Browser Storage Apis is an important topic to understand.
- Start with small examples and practice one step at a time.
- Use the idea in simple projects so it becomes easier to remember.