What is the mechanism to store the data on the client’s browser in HTML ?
Server-side storage stores data on the server (i.e. an external database) and client-side storage allow the user to store data on the client (i.e. user’s browser).
- Personalizing site preferences (for example: showing a user’s choice of custom widgets, color scheme, or font size).
- Persisting previous site activity (for example: storing the contents of a shopping cart from a previous session and remembering if a user was previously logged in).
- Saving web application-generated documents locally for offline use.
- Saving data and assets locally so that users will be quicker and less expensive to download, or sometimes used without a network connection.
Web storage and cookies are two ways to store the data in the client browser. They are explained below:
Web Storage: With the help of web storage, web applications can store data locally within the user’s browser. During every server request data is stored in the form of cookies.
- Web storage is more secure, and large amounts of data can be locally stored, without affecting website performance.
- The storage limit is larger (at least 5MB) and the information is never transferred to the server.
- The same data is accessed by the pages from the same origin.
The first browser version fully supports Web Storage is given below:
- Chrome: 4.0
- Firefox: 3.5
- Safari: 4.0
- Opera: 11.5
- Internet Explorer/Edge: 8.0
HTML Web Storage Objects: HTML web storage has two objects for storing data on the client:
- window.localStorage: There is no expiry date for the data stored.
- window.sessionStorage: It stores data for one session (data is lost when the browser tab is closed)
First check browser support for localStorage and sessionStorage:
The localStorage Object: The localStorage object stores the data with no expiry date. The data is not deleted even when the browser is closed.
The sessionStorage Object: It stores the data for only one session. The data is deleted whenever the user closes the specific browser tab.
Cookies in HTML: Cookies are the data stored in small text files on the computer. They were invented to remember the information of the user. Because when a web server sends the data to the browser and if by any external factors shuts down then the server forgets everything about the user.
When a user visits a web page his data is stored in the form of a cookie. If the same user visits the web page again then the web page remembers the user and provides feeds related to the previously searched items. These cookies are exchanged between web browsers and web servers. Cookies are saved in name-value pairs as:
username = geek
The <meta> tag can be used to store the cookies on the client-side.
Example: In the example below, The value entered in the name field is stored as the cookie in the browser.