Web storage in HTML5 allows you to locally store information on the user's computer, similar to cookies, but with faster and more efficient performance. However, it's important to note that while web storage offers advantages over cookies, it doesn't necessarily enhance security compared to cookies. For more insights into cookies, you can refer to the PHP cookies tutorial.
Unlike cookies, the data stored in web storage is not sent to the web server with every request. Additionally, while cookies have a size limitation of around 4KB, web storage enables you to store up to 5MB of data.
There are two types of web storage, each with different scopes and lifetimes:
localStorage
object to store data for the entire website on a permanent basis. This means the stored data will persist beyond individual browsing sessions.sessionStorage
object to store data temporarily, limited to a single browser window or tab. Data stored in session storage is cleared when the session ends, such as when the user closes the browser window or tab.Tip: Web storage features are supported in all major modern web browsers, including Firefox, Chrome, Opera, Safari, and Internet Explorer 8 and above.
With the localStorage object, data is stored without an expiration date, organized as key/value pairs. Each piece of data is identified by a key (e.g., 'first_name'), with the associated value (e.g., 'Peter'). Here's an example:
<script>
// Check if the localStorage object exists
if(localStorage) {
// Store data
localStorage.setItem("first_name", "Peter");
// Retrieve data
alert("Hi, " + localStorage.getItem("first_name"));
} else {
alert("Sorry, your browser does not support local storage.");
}
</script>
The provided JavaScript code accomplishes the following:
If necessary, you can remove a specific item from storage using the removeItem()
method by passing the key name (e.g., localStorage.removeItem("first_name")
). To clear the entire storage, use the clear()
method (e.g., localStorage.clear()
), although exercise caution as it removes all key/value pairs at once.
Note: Data stored in web storage (both localStorage and sessionStorage) is not shared between different browsers. For example, data stored in Firefox will not be accessible in Google Chrome, Safari, Internet Explorer, or other browsers.
The sessionStorage
object operates similarly to localStorage
, but stores data for only the duration of a single session, which ends when the user closes the browser window or tab.
Explore the following example to gain a basic understanding of its functionality:
<script>
// Check if the sessionStorage object exists
if(sessionStorage) {
// Store data
sessionStorage.setItem("last_name", "Parker");
// Retrieve data
alert("Hi, " + localStorage.getItem("first_name") + " " + sessionStorage.getItem("last_name"));
} else {
alert("Sorry, your browser does not support session storage.");
}
</script>