Using Local Storage to Save and Load Data
The W3Schools site introduces the use of local storage for temporary and permanent storage. This page covers only permanent storage. Although you use local storage to save name/value pairs of strings, the value string can be large and can be a comma-separated list to represent the contents of an array. This is how we used it in our third Smart Pascal demonstration. We base this JavaScript on that demo.
<!DOCTYPE html> <html> <body> <p id = "colours"> <p id = "colour5"> <p id = "rainjanfeb"> <script>
var arrColours = ['aqua', 'black', 'blue', 'fuchsia', 'green', 'gray', 'lime']; var strColours = arrColours.join(); var loadedStrColours; var loadedArrColours = []; var arrRainfall = [61, 36, 50, 42, 45, 46, 46, 44, 43, 73, 45, 59]; var strRainfall = arrRainfall.join(); // Treats numbers as strings var loadedStrRainfall; var loadedArrRainfall = []; //Colours (strings) first // Save if not already saved if (!localStorage.colors) { localStorage.setItem('colors', strColours); alert('Saving data for the first and only time in this browser'); // Load loadedStrColours = localStorage.getItem('colors'); document.getElementById('colours').innerHTML = loadedStrColours; loadedArrColours = loadedStrColours.split(','); document.getElementById('colour5').innerHTML = 'Colour with array index 5: ' + loadedArrColours[5]; // Now the numbers if (!localStorage.rainfall) localStorage.setItem('rainfall', strRainfall); loadedStrRainfall = localStorage.getItem('rainfall'); loadedArrRainfall = loadedStrRainfall.split(',').map(Number); //Neatly converts strings to numbers document.getElementById('rainjanfeb').innerHTML = 'Rainfall for Jan and Feb: ' + (loadedArrRainfall[0] + loadedArrRainfall[1]);
</script> </body> </html>