Last Updated : Jul 1, 2023
Whenever a visitor closes your site, you will still be able to access the data you have stored.
The purpose of this tutorial is to demonstrate how you can access persistent data using only client-side code to store and retrieve data.
The localStorage object is supported by most web browsers as part of their web storage API.
By storing data in localStorage, you can create key-value pairs. It is recommended to use UTF-16 DOM Strings for unique keys and values.
By using the JSON.stringify() method, you can convert objects and arrays to strings.
LocalStorage supports data storage of up to 5MB. A site's localStorage data can also be shared between all windows which share the same origin.
In spite of the fact that a user closes the browser, this data will not be deleted. The website that created the file will be able to access it anytime in the future.
The localStorage method may be useful for saving sensitive data, but other scripts that run on the same page will be able to access it as well.
Data stored in localStorage can be read by calling the method getItem(). A string value is returned as a result of this method, which accepts the key as a parameter.
By using the setItem() method, data can be stored in localStorage. Keys and corresponding values are passed as arguments to this method.
The removeItem() method can be used to delete a localStorage session. You need to pass the key as a parameter to this method to delete the key-value pair. If the key exists, the process will delete the key-value pair.
The key() method accepts the index as an argument and returns the corresponding key.
The getItem() method accepts the key as an argument and returns the corresponding value. Lastly, the console.log() method prints the key-value pair.
- We start by writing <HTML>, which tells the browser what HTML version we're using. Tags are the beginning of HTML documents.
- This is followed by the <body> tag that defines the body of the webpage.
- Then we use an onclick directive for detecting click events and an ng-class directive for adding up and down arrows. ng-click and ng-class directives contain a function that takes the key name as a parameter.
- Then we use <p> for creating paragraph.
- After that </script></body></html> and code should be executed after closing all tags.
The local Storage object has several methods including setItem(), getItem(), removeItem(), and clear().
While local Storage is easy to use, it is not safe to store sensitive information. But it's a good choice to develop projects that don't require much storage and don't involve any sensitive information.