
Saving data to browser local storage using javascript
As website developers, every now and then we come across instances when we need to store some information and want it to persist through out the site.
The ideal way to do this is use server side code like PHP or C#. However, how can you easily achieve this if your website is build using HTML. I faced this issue and kept on searching for an optimal solution for this which had to be quick and easy to implement and did not need be to install any extra resource or plugins.
Javascript to the rescue as always. So the below script will allow you to add, get and delete data stored in the browser local cache. This data can be easily persisted while the user navigates to different pages of the website.
<script type=”text/javascript”>
function AddToCacheCustom(key, value) {
localStorage[key] = value;
};
function GetCacheCustom(key)
{
if (localStorage[key] !== undefined && localStorage[key] !== null)
{
return localStorage[key];
}
return null;
};
function DeleteCacheCustom(key)
{
localStorage[key] = null;
};
</script>
That’s it. Now you can use the AddToCacheCustom method which takes a key and value to save data to the local cache. Then use GetCacheCustom to fetch the value by passing in the key. And if needed delete data from the cache using the DeleteCacheCustom method.
0 Comments
Be the first to comment