Web APIs
JS Web Storage API
Web Storage with localStorage
JavaScript Web Storage API uses localStorage, with size limits.
Introduction to Web Storage API
The JavaScript Web Storage API provides a way to store key/value pairs in the browser. It offers two storage options: localStorage
and sessionStorage
. Both are designed to be more intuitive and efficient than cookies. Here's how they differ:
- localStorage: Data persists even after the browser is closed and reopened. It has no expiration time.
- sessionStorage: Data is stored for the duration of the page session. Once the tab or window is closed, the data is lost.
Using localStorage
The localStorage
object stores data with no expiration date, and it's accessible across different browser windows and tabs. Here are some basic operations:
Limitations of localStorage
While localStorage
is useful, it comes with limitations:
- Storage limits vary by browser, typically around 5-10 MB per domain.
- Stored data is accessible from any script on the same domain, so avoid storing sensitive information.
- Data is stored as strings, so you need to serialize and deserialize objects using
JSON.stringify()
andJSON.parse()
.
Example: Saving User Preferences
Let's look at an example where we save a user's theme preference:
Using sessionStorage
The sessionStorage
object works similarly to localStorage
but is limited to the duration of the page session. It is useful for storing temporary data:
Conclusion
The JavaScript Web Storage API is a powerful tool for client-side data storage, offering both localStorage
and sessionStorage
for different use cases. While it provides a simple way to store data, developers must be mindful of its limitations, especially regarding data size and security.
Web APIs
- Previous
- Popup Alert
- Next
- Web Geolocation API