This is a simple example of how to set and get data from HTML5 local storage.
In HTML5, we have 5 MB of local storage available per domain.
Unlike cookies, the data in local storage is never transferred to the server unless your write code to do that.
All pages on the same domain can read and write data to the HTML5 local storage. This feature is supported in all modern browsers.
Below is a simple example of how to Set and Get data from a web browser’s Local Storage using JavaScript:
I have some output going to the page but you’ll need to view the JavaScript console in the browser to see all of the data.
<html>
<script>
const eightiesMoviesThatHoldUp = [
'Aliens',
'Ghostbusters',
'Labyrinth',
'Mad Max Beyond Thunderdome',
'The Goonies',
'The Lost Boys'
];
const yearSelected = 1986;
const movieSelected = 'Aliens';
//Add itesm to loca storage
localStorage.setItem('moviesArray', eightiesMoviesThatHoldUp);
localStorage.setItem('movie', movieSelected);
localStorage.setItem('year', yearSelected);
//Get items from local storages, assign to variables
const moviesArray = localStorage.getItem('moviesArray');
const movie = localStorage.getItem('movie');
const year = localStorage.getItem('year');
console.log(moviesArray);
console.log(movie);
console.log(year);
console.log('----------');
//convert string in storage to an array variable using split
console.log(moviesArray.split(','));
console.log(movie);
//Use parseInt to convert string in to integer value
console.log(parseInt(year,10));
//Removing item from local storage
console.log('----------');
localStorage.removeItem('moviesArray');
const newMoviesArray = localStorage.getItem('moviesArray');
console.log(newMoviesArray);
Clear all storage items for domain
localStorage.clear();
const finalMoviesArray = localStorage.getItem('moviesArray');
const finalMovie = localStorage.getItem('movie');
const finalYear = localStorage.getItem('year');
console.log(finalMoviesArray);
console.log(finalMovie);
console.log(finalYear);
</script>
<body>
<!--// https://www.youtube.com/watch?v=NFqeGLDnj-I //-->
<div>
<p id="reminder">Make sure to open your browser's Javascript console!</p>
</div>
<div id="output"></div>
</body>
<script>
document.getElementById("output").innerHTML = localStorage.getItem('movie') + " " + localStorage.getItem('year') ;
</script>
</html>