HTML5 Local Storage
Local Storage is a web storage feature that allows you to store key-value pairs in a web browser. It’s part of the Web Storage API and provides a way to persist data across sessions without an expiration date, meaning the data will remain until explicitly deleted.
Key Features of Local Storage:
- Capacity: Generally allows around 5-10 MB of data per origin.
- Synchronous API: Access to data is synchronous, meaning it can block the main thread, so it's best for smaller amounts of data.
- Data Type: Only stores strings. You can use JSON to store objects or arrays.
- Persistence: Data persists even after the browser is closed and reopened.
- Scope: Data is scoped to the origin (protocol, host, and port), so different domains cannot access each other’s Local Storage.
Common Methods:
localStorage.setItem(key, value)
: Stores a value with the specified key.localStorage.getItem(key)
: Retrieves the value associated with the specified key.localStorage.removeItem(key)
: Removes the specified key and its value.localStorage.clear()
: Removes all key-value pairs from Local Storage.
Example Usage:
// Storing datalocalStorage.setItem('username', 'JohnDoe');// Retrieving dataconst username = localStorage.getItem('username');console.log(username); // Outputs: JohnDoe// Removing datalocalStorage.removeItem('username');// Clearing all datalocalStorage.clear();
Use Cases:
- Storing user preferences.
- Caching data for offline access.
- Managing user sessions.
Keep in mind that sensitive information should not be stored in Local Storage due to security concerns, as it's accessible via JavaScript.
HTML5 Session Storage
Session storage is a type of web storage that allows you to store data for the duration of a page session. This means that the data persists as long as the browser tab is open. Once the tab is closed, the data is cleared.
Here are some key points about session storage:
Scope: Data is limited to the window or tab where it was created. Different tabs or windows will not share the same session storage.
Storage Limit: Typically, session storage can hold around 5-10MB of data, though this can vary by browser.
Data Types: You can only store data as strings. To store objects, you'll need to convert them to strings using
JSON.stringify()
and parse them back usingJSON.parse()
.API: You can access session storage using the
window.sessionStorage
object. Common methods include:setItem(key, value)
: Store a value by key.getItem(key)
: Retrieve a value by key.removeItem(key)
: Remove a specific item by key.clear()
: Clear all session storage data.
Use Cases: It's commonly used for temporary data, such as user preferences, form inputs during a session, or any data that should not persist beyond the tab being open.
0 comments:
Post a Comment