Καλώς ορίσατε στο dotNETZone.gr - Σύνδεση | Εγγραφή | Βοήθεια

C# and .NET Tips and Tricks

Quests in programming in .NET
HTML5 Client Storage. An introduction on the new cookies.

Let’s talk about cookies. In fact let’s revisit cookies and see how we use them and what nightmares they bring along. Cookies are all about client storage. They are all about storing persistent information at client side.

The syntax for creating/reading them is as follows. Imagine that we want to store client side the value 17 in a cookie named id. This is done by the following BLOCKED SCRIPT document.cookie=”id=17;expires=Mon,6 Feb 2012 12:00:00”;

When we later want to read the value of the cookie named id we need to search within document.cookie for the string “id=” and fetch the value up to the next “;” character.

Based on the previous definitions we may come up with three nice Javascript functions that make our lives a littler easier:

Creating a cookie

function SetCookie(name, value, expirationInDays) {
    var now = new Date();
    var expire = new Date();
    var newCookie = name + "=" + value;
    if (expirationInDays != null && expirationInDays != 0) {
        expire.setTime(now.getTime() + 3600000 * 24 * expirationInDays);
        newCookie += ";expires=" + expire.toGMTString();
    }
    document.cookie = newCookie;
}

Reading the value of a cookie

function ReadCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = caIdea;
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
}

Or of course you can use a JQuery plugin which provides an implementation for the basic operations with cookies.

Now some basic facts:

 

  • To update a cookie you just create the same cookie with the updated value.
  • If you do not define an expiration date then the cookie will expire as soon as the browser’s window is closed. This cookie is also called a session-based cookie.
  • if you want to delete a cookie then you must call SetCookie for the cookie without providing an expiration date and by setting its value to blank. As a consequence the cookie will be removed when the browser’s window is closed (so it is actually an inferred delete!)
  • Cookies persist among tabs in a browser. So storing tab critical information in the cookie may result in unwanted behavior.

 

So we need a better and easier way to create/update/delete values that we store client-side, and easier way to handle expiration (values that persist even when the browser is closed or values that they don’t). And that is exactly what HTML5 offers us through the use of the following:

 

  • sessionStorage: Equivalent to session-based cookies. Is erased when the browser window is closed but also the values are not shared among browser’s tabs.
  • localStorage: Equivalent to cookies with expiration date but does not expire.

 

The API is native to Javascript and is as follows (for the same example with the value 17 called id). For sessionStorage just replace localStorage with sessionStorage:

 

  • Create: localStorage.setItem("id",17);
  • Read: localStorage.getItem(“id”);
  • Remove: localStorage.removeItem(“id”);
  • Clear all:localStorage.clear();

 

Finally don’t forget that like cookies in those values you can even store full Javascript objects as follows where we store the object Client in sessionStorage using JSON.stringify and retrieve it with :

var Client = {
    firstName:"John",
    lastName:"Panagopoulos",
    coolFactor:10
}
function storeClient() {
    sessionStorage.setItem("client", JSON.stringify(Client));
}
function getClient() {
    var retrievedClient = JSON.parse(sessionStorage.getItem("client"));
    console.dir(retrievedClient);
}

Well this is it. Of course there are some other sophisticated methods to store stuff client-side the “HTML5” way such as Web SQL Databases or the cache but we will cover those in a future post.

Share
Posted: Δευτέρα, 6 Φεβρουαρίου 2012 2:22 μμ από το μέλος iwannis
Δημοσίευση στην κατηγορία:

Σχόλια:

Χωρίς Σχόλια

Ποιά είναι η άποψή σας για την παραπάνω δημοσίευση;

(απαιτούμενο)

(απαιτούμενο)

(προαιρετικό)

(απαιτούμενο)
ÅéóÜãåôå ôïí êùäéêü:
CAPTCHA Image

Ενημέρωση για Σχόλια

Αν θα θέλατε να λαμβάνετε ένα e-mail όταν γίνονται ανανεώσεις στο περιεχόμενο αυτής της δημοσίευσης, παρακαλούμε γίνετε συνδρομητής εδώ

Παραμείνετε ενήμεροι στα τελευταία σχόλια με την χρήση του αγαπημένου σας RSS Aggregator και συνδρομή στη Τροφοδοσία RSS με σχόλια