Contenido del Curso
HTML & JavaScript Interactivity for Beginners
HTML & JavaScript Interactivity for Beginners
HTML Web Storage
Now with the HTML 5 web storage facility, you can also store the data locally in your browser. Suppose you were filling out an online form and lost the internet connection due to some network error. However, when you come back, you don't have to fill the form from the beginning, as the form values you already filled will be saved.
Before the advent of web storage API, cookies were used for this purpose. But cookies data storage was minimal compared to web storage which can store at least 5MB of data. Also, unlike cookies, the data doesn't have to travel to and from the server.
Now let's start with the two types of web storage.
What are the two types of Web Storage?
HTML Web Storage API provides two objects for storing data on the client side. They are:
window.localStorage
: provides methods to save and retrieve data with no expiration date. Stores only the text data;window.sessionStorage
: provides methods to save and retrieve session data for the duration of the session only. On closing the browser window, the session expires. Again it stores only the text data.
How does Local Storage Work?
The localStorage
object stores data with no expiration date in key-value pairs using the setItem method. Here's the code:
To get the stored values, you use getItem
method as below:
Local Storage Example with JavaScript
In this example, we'll create an input box and store its value when a user clicks the save button. Then suppose you exit the page and come back; the code will retrieve the data.When the page loads, it will check if the local storage object has been set. If so, it'll show the value in the <textbox>
.
index
index
index
Unlike the local storage objects, the session storage objects' data will disappear when the browser tab is closed. Then, why do you need a session object in the first place?
Well, the session object improves the security as, unlike the local storage, you will not be able to save personal data on your device, which may lead to security issues. The other fact is that if a user changes a specific setting on a page, such as its background color or the template design, once they reload the page, it will return to the original settings.
Now let’s dive into an example with session storage.The methods setItem
and getItem
remain the same.
Session Storage Example with JavaScript
In this example we’ll change the font color of the paragraph element based on the user selection.
index
index
index
¡Gracias por tus comentarios!