05 June 2016

Accessing the local storage

 Introduction

Sometimes it's quite useful to store some information on the visitors computer. Maybe you want to store the whole shopping cart on the computer. Maybe you make a website, where you can change the background color to pink for yourself. Maybe you want store the highscore of klicking the "Get me out of here"-button.
A common method is storing the information in a cookie. Yeah, you probably heard of those evil cookies that's only purpose is to get ALL of your personal information, like your prefered socks color, your credit card number and which super hero you are. Like your mother warned you about playing with the neighbours kid, some "IT specialists" warn you about accepting cookies.
Here comes the fun fact. We won't using cookies. Although it will work the same way.

What can it do?

The local storage is a key-value based database that modern browsers (and the IE) implements. Like cookies, the storage is bound to your website. When you store data in it, it cannot be recieved though another website.

The local storage is called localStorage (oh wonder..) and is a child of the window object. It has only four methods.

For storing
window.localStorage.setItem(<key>, <value>)

For recieving the value
window.localStorage.getItem(<key>)

For deleting a key-value pair
window.localStorage.removeItem(<key>)

For flushing all your stored data down the toilet
window.localStorage.clear()

You can save text in it. Not much? Want store complex objects? Easy! Use JSON to store and recover your objects.

Requirements

None. You just need JS and a browser, that supports localStorage.

Code

In this example you have an input where you can type in a message. With the save-button you store the message in the storage. With the load-button you can retrieve the message and put it in the text field again.
Although localStorage doesn't need any jQuery, we use it to minimize the code.

html
<input type="text" id="vault" />
<button onclick="save();retur

n false;">Save</button>
<button onclick="load();return false;">Load</button>

js
function save() {
        // saving what's in the input-field "vault" to the "myVault" in the local storage
        window.localStorage.setItem("myVault", $("#vault").val());
    }

    function load() {
        // retrieving what's in the myVault" of the local storage and put it in the input "vault"
        $("#vault").val(window.localStorage.getItem("myVault"));
    }


Be aware!

Not all browsers support the local storage. If you want to use it, mage certain it will work in your site.
How to check it? Simple...
js
if(window.localStorage){
    // shit works
}
else{
   // here, we have a problem...
}

No comments:

Post a Comment

Amazon