About Me

I have decades of experience is software development using .Net Technologies, PHP and wordpress. I love coding and discovering new tech.

Blog

Saving data to browser local storage using javascript

Coding, Javascript

Saving data to browser local storage using javascript

Posted on September 14, 2022  - By Kaustav Halder - 0 Comments

How to save data on browser local storage for your HTML Website?

Overview

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.

The Code

<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.



About Kaustav

I have decades of experience is software development using .Net Technologies, PHP and wordpress. I love coding and discovering new tech.


0 Comments

Be the first to comment


Leave a reply

Leave a Reply

Your email address will not be published. Required fields are marked *