Saturday, 23 August 2014

Making our Web Storage API app cooler!


So, you have a cool website that can store stuff and magically display it back to the user even if they navigate away from the webpage and revisit you.

But if they close the browser all of your data just goes away like volatile memory! (I don't expect you to understand the last 2 words though..).

So, here in this post, we'll make our app really cool and make it store the data even if the browser or even the computer is shut down!

The only thing you'll have to change is replace all of the 'sessionStorage's with 'localStorage'.

The main difference between session storage and local storage is that local storage can store data forever.
However:
"With great power comes great responsibility..."
Now let me explain in plain English what I meant. When we used session storage neither of us had to bother to delete the variables because they'd all be gone when the person closes his browser. But now that our variables stay forever the person using our app wont be able to delete the variables by closing his browser.

So this implies that unless your user is an expert JavaScript programmer aware of his browser's developer tools he wont be able to delete your variables which sounds really creepy and it is.

Hence, we'll also have to provide a way to clean up variables by offering a "Delete" link to delete the variables to be a good citizen of the internet.

So, let's modify our for loop in our disp function. All we have to do is append a link that says delete that calls a function called deleteVar that takes in a key to delete.

So this is what that looks like:
for(var i=0; i < localStorage.length; i++){
    var key = localStorage.key(i);
    var val = localStorage.getItem(key);

    var link = '<a href="javascript:deleteVar(\''+key+'\')">Delete</a>';

    box.innerHTML += key+": "+val+" "+link+"<br />";
}

Building the delete function

Now, if you don't know how to delete stuff using the web storage API you should really check my overview of web storage API that I'd done long ago.

Now that you know how to delete stuff using web storage API building the deleteVar function would've become really easy.

Here's what it looks like:
function deleteVar(key){
    localStorage.removeItem(key);
    
    // Call the disp function to update the box
    disp();
}
Here's the whole package: View Demo

No comments:

Post a Comment