Computers Windows Internet

Local storage. Using localStorage for JavaScript needs Cookie local storage

The cookies that we analyzed in the previous lesson are very limited: there can be only 4096 characters in one cookie, and the number of cookies per domain can be about 30-50 depending on the browser. Therefore, alas, it will not be possible to store a lot of information there. It so happened historically.

To get around this limitation, an alternative to cookies has appeared in browsers - it is called local storage. In local storage, we can store 5-10 megabytes of information or even more for a long time.

Working with local storage

The localStorage object built into the browser is intended for working with local storage. It has 4 easy-to-understand methods. Here they are:

// Store the value: localStorage.setItem ("Key", "Value"); // Get the value: var value = localStorage.getItem ("Key"); // Remove value: localStorage.removeItem ("Key"); // Clear all storage: localStorage.clear ();

WITH localStorage you can also work like a regular array:

// Store the value: localStorage ["Key"] = "Value"; // Get the value: var value = localStorage ["Key"]; // Delete value: delete localStorage ["Key"];

Besides the object localStorage there is also an object sessionStorage... Working with it is carried out in the same way, the only difference is that all data from it is automatically destroyed after closing the browser or the tab with the site. Well, localStorage stores data for a long time until this data is deleted by a script, or the browser user clears the local storage using the settings.

Examples of

In the following example, we will write the username to local storage:

LocalStorage.setItem ("name", "Ivan");

After a while, we will get this name back:

Alert (localStorage.getItem ("name"));

As you can see, there is nothing complicated here, everything is much simpler than the same work with cookies.

Saving objects

Local storage is not capable of storing JavaScript objects and arrays, although this is often convenient. But there is a way - you need to serialize this data into JSON format - you get a string that can already be stored in localStorage. Then, when we need to get this object back - convert the string from JSON back to an object - and use it calmly.

Let's take a look at this process with an example. Serialize the object and save it to local storage:

// Given an object: var obj = (name: "Ivan", arr :); // Serialize it to "(" name ":" Ivan "," arr ":)": var json = JSON.stringify (obj); // Write to localStorage with the obj key: localStorage.setItem ("obj", json);

After a while, we get the object back:

// Get the data back from localStorage as JSON: var json = localStorage.getItem ("obj"); // Convert them back to JavaScript object: var obj = JSON.parse (json); console.log (obj);

Additional features

Determining the number of records in the storage: alert (localStorage.length).

Determining the name of the key by its number: alert (localStorage.key (number)).

When performing operations with the storage, the event is triggered onstorage... If you bind a function to this event, then the Event object with the following properties will be available in it:

function func (event) (var key = event.key; // key of the data being changed var oldValue = event.oldValue; // old value var newValue = event.newValue; // new value var storageArea = event.storageArea; // storageArea )

Add. material

Storing the array in local storage: https://youtu.be/sYUILPMnrIo

What to do next:

Start solving problems at the following link: tasks for the lesson.

When you have decided everything, move on to studying a new topic.

Some videos may be running ahead, as we have not gone through all ES6 to this place in the tutorial. Just skip these videos, watch them later.

Web Storage Overview

On the Internet, information can be stored in two places: on the web server and on the web client (i.e. the computer of the page visitor). It is best to store certain types of data in one of these places, and other types in another.

The right place to store sensitive and important data is a web server. For example, if you add items to your shopping cart in an online store, your potential purchase data is stored on a web server. Only a few bytes of tracking data is stored on your computer, containing information about you (or rather, about your computer) so that the web server knows which bucket is yours. Even with the new capabilities of HTML5, there is no need to change this system - it is reliable, secure and efficient.

But storing data on a server is not always the best approach. sometimes it is easier to store non-essential information on the user's computer. For example, it makes sense to store user preferences (say, settings that determine how a web page is displayed) and application state (a snapshot of the current state of the web application) locally so that the visitor can continue from the same place later.

Before HTML5, the only way to store data locally was using the file mechanism cookies which was originally designed to exchange small amounts of identifying information between web servers and browsers. Cookies are ideal for storing small amounts of data, but the JavaScript model for working with them is somewhat clunky. The cookie system also forces the developer to fiddle with expiration dates and uselessly send data back and forth over the internet with every page request.

HTML5 introduces a better alternative to cookies, which makes it easy and simple to store information on a visitor's computer. This information can be stored on the client computer indefinitely, is not sent to the web server (unless the developer does it himself), it can be large and requires only a couple of simple, efficient JavaScript objects to work with.

This opportunity is called web storage and is particularly suitable for use with offline mode work of websites, because allows you to create self-contained standalone applications that can save all the information they need even when there is no internet connection.

The HTML5 web storage functionality allows a web page to store data on a visitor's computer. This information can be short-term, which is deleted after turning off the browser, or long-term, which remains available on subsequent visits to the web page.

The information stored in the web storage is not actually stored on the Internet, but on the computer of the web page visitor. In other words, web storage does not mean storing data on the Internet, but storing data from the Internet.

There are two types of web storage that are somehow associated with two objects:

Local storage

Uses object localStorage to store data for the entire website on a permanent basis. This means that if a web page saves data to local storage, that data will be available to the user when they return to that web page the next day, next week, or next year.

Of course, most browsers also provide the user with the option to clear local storage. In some browsers, it is implemented as an all-or-nothing strategy, and it deletes all local data, much like a cookie is deleted. (In fact, in some browsers, cookies and local storage are interconnected, so the only way to delete local data is to delete cookies.) Other browsers can provide the user with the ability to view data for each individual website and delete data for the selected site or sites.

Session data store

Uses object sessionStorage to temporarily store data for a single browser window or tab. This data is available only until the user closes the window or tab, after which the session ends and the data is deleted. But session data persists if the user navigates to another website and then returns back, provided that this happens in the same browser window.

From the point of view of the web page code, both local storage and session data storage work exactly the same. The only difference is in the duration of the data storage.

Using local storage provides best opportunity to save the required information for subsequent visits to the website by the user. And the session store is used to store data that needs to be transferred from one page to another. (Session store can also store temporary data used by only one page, but regular JavaScript variables work just fine for this purpose.)

Both local storage and session storage are associated with the domain of the website. Thus, if you save the data for the www..html page in the local storage, this data will be available for the www..html page, since both of these pages have the same domain. But this data will not be available for pages of other domains.

In addition, since web storage is located on your computer (or mobile device) given user, it is associated with this computer, and the web page opened on this computer and storing data in its local storage, does not have access to the information that it has stored on another computer. Likewise, the web page creates a separate local store if you log in with a different username or launch a different browser.

While the HTML5 specification does not set any hard and fast rules for maximum storage, most browsers limit it to 5MB. You can pack a lot of data into this volume, but it won't be enough if you want to use local storage to optimize performance and cache large images or videos in it (and, in truth, local storage is not designed for such purposes).

A still evolving database standard for storing large amounts of data IndexedDB Allows much more local storage - typically 50 MB to start with and more if the user agrees.

Saving data

Before you put a piece of information into local or session storage, you need to give it a descriptive name. This name is called a key and is needed so that the data can be retrieved in the future.

The syntax for saving a chunk of data is as follows:

localStorage = data;

// JS localStorage ["username"] = "Ivan Petrov";

Of course, it makes no sense to save a piece of static text. As a rule, we need to save some kind of variable data, for example, the current date, the result of a mathematical calculation, or text data entered by the user into the form fields. The following is an example of storing user-entered text data:

Web storage

Function saveData () (// Get the values ​​of the text boxes var localData = document.getElementById ("localData"). Value; var sessionData = document.getElementById ("sessionData"). Value; // Save the text entered in the text box into local storage localStorage ["localData"] = localData; // Save the text entered in the text field to the session storage sessionStorage ["sessionData"] = sessionData;) function loadData () (// Load the saved data from the storages var localData = localStorage ["localData"]; var sessionData = sessionStorage ["sessionData"]; // Display this data in text fields if (localData! = null) (document.getElementById ("localData"). value = localData;) if (sessionData! = null) (document.getElementById ("sessionData"). value = sessionData;))

The page contains two text boxes: for local storage (top) and for session storage (bottom). Clicking the Save button saves the text entered in the text fields, and clicking the Load button displays the corresponding saved data in the fields.

Web Storage also supports the less common property syntax. According to the rules of this syntax, we refer to the storage location named username as localStorage.username, not localStorage ["username"]. Both types of syntax are equivalent, and the use of one or the other is a matter of personal preference.

Web storage does not work without a web server

In your research on web storage, you might run into an unexpected problem. In many browsers, web storage only works for pages provided by the web server. In this case, it does not matter where the server is located, on the Internet or on your own computer, the most important thing is that the pages are not launched from the local hard disk(for example, double click by the page file icon).

This feature is a side effect of the way browsers allocate local storage space. As previously stated, browsers limit local storage for each website to 5MB by associating each page that wants to use local storage with the website's domain.

What happens when you open a page that uses web storage from your local hard drive? It all depends on the browser. Browser Internet Explorer seems to be losing web storage support entirely. The localStorage and sessionStorage objects disappear and trying to use them throws a JavaScript error.

In Firefox, the localStorage and sessionStorage objects remain in place and seem to be supported (even Modernizr detects that they are supported), but whatever is sent to storage disappears to no one knows where. V Chrome browser again, something different - most of the functionality of web storage works as it should, but some features (for example, the onStorage event) do not work.

Similar problems arise with the File API. Therefore, you save yourself a lot of hassle if you put the page under test on a test server to avoid all these ambiguities.

Web storage support by browsers

Web Storage is one of the most supported HTML5 features, with a good level of support in every major browser. The table below shows the minimum versions of the major browsers that support web storage:

All of these browsers provide local and session data storage capability. But to support the onStorage event, later versions of browsers are required, such as IE 9, Firefox 4, or Chrome 6.

The most problematic is IE 7, which does not support web storage at all. As a workaround, you can emulate web storage using cookies. This is not really a perfect solution, but it works. While there is no official script to close this gap, some good starting points can be found on the HTML5 Cross Browser page (under "Web Storage").

Translation of the article: How to use local storage for JavaScript.
Sara Vieira.

Familiarity with the basics of JavaScript programming often starts with creating the simplest applications, such as the electronic notebook, which we use to record things and events that we can forget about. But such applications have one problem - after reloading the page, the list of all previously left records disappears, that is, the application returns to its original state.

There is a very simple way out of this situation by using the localStorage mechanism. Due to the fact that localStorage allows us to store the necessary data on the user's computer, the above list of scheduled tasks and events will still be available after reloading the page, in addition, localStorage is a surprisingly very simple way of storing data and accessing it when needed.

What is localStorage?

It is a local storage engine that is part of the Web Storage technology as defined by the HTML5 specification. There are two storage options allowed by this specification:

  • Local storage: allows you to save information without restrictions on storage periods. We will use this option, since the list of tasks available in our example should be stored permanently.
  • Using sessions: ensures the safety of data only for the period of one session, that is, after the user closes the tab of our application and reopens it, everything necessary for further work application information will be deleted.

Simply put, everything Web Storage does is store data in the form named key / value locally and unlike the other two methods, each of which has its drawbacks ( Session storage of information provides for the use of the server side for this, besides, after the user's session is closed, this information is deleted, and although cookies are used for storage on the client side, they are not reliable because the user can cancel their support through the browser settings.) saves data even if if you closed your browser or turned off your computer. ( * I took the liberty of slightly changing and supplementing the content of this paragraph, since I believe that the author made some inaccuracies in the original.)

Html

If we stick to our example, in which we want to create an electronic version notebook, then all the necessary components for its implementation are presented below:

  • A field for entering new records (events, cases, etc.).
  • Button to confirm the entered entry.
  • Button for clearing an already created to-do list.
  • An unordered list that will be populated with new entries.
  • Finally, we need a div as a container to contain messages to be displayed to the user, such as a warning that he forgot to enter the value for the next record, leaving the input field blank.

As a result, our markup should look something like this:








This is a pretty standard HTML template that we can fill with dynamically generated content using JavaScript.

JavaScript

Regarding the structure of the simplest notepad application in our example, the first thing we need to do is to ensure that the button click event is tracked. "Add a note" and check if any information is entered into the text field for recording, that is, at the moment of pressing the button, it should not be empty. Something like this:

$ ("# add"). click (function () (
// if the text field is empty
$ ("# alert"). html (" Attention! Enter the entry in the text
field.");
return false;
}

Here's what we do with this piece of code. When the button is pressed "Add a note" we check if the user has entered anything in the field for the new record. If he did not do this, then the div provided by us for displaying messages appears, informing the user that the input field of the record is not filled and then, after 1000ms (1 second), the div element, and accordingly the message, disappears. The function then returns false, after which the browser stops executing the rest of the script and the application is again ready to enter a new record.

Our next step is to add the value entered in the record field to the beginning of the list by generating a new list item. Thus, when the user adds another entry, it will always be placed at the beginning of the list of to-do and expected events. After that, we just have to save the list using the localStorage mechanism:

// Add an entry to the existing list
$ ("# todos"). prepend ("

  • "+ Description +"
  • ");
    // Clear the input field
    $ ("# form"). reset ();

    return false;
    });

    As you may have noticed, there is nothing unusual here, it is used standard version jQuery code. At the point of accessing the localStorage object, we must specify the data we are saving in the form of a key / value. An arbitrary name can be used for the key, and I named it "todos", then we need to indicate what we, in fact, need to keep in memory. In this case, it is a complete piece of HTML markup, included in an unordered list (located between tags), which displays all the entries previously entered by the user. From the code, you can see that we simply retrieve the fragment we need using the jQuery .html () method and at the end, after completing all the necessary actions, we set the return value of the function to false, which prevents the form data from being submitted and, therefore, our page reloading.

    Now, let's say our user has previously made several entries and for the further normal operation of the application, we need to check whether there is information stored on the computer in localStorage and, if so, display it for the user. Since the name of our key is "todos", we must check for its existence as follows:

    // if there is already data in the local storage, then display it

    }

    To check for the presence of data, we used the usual if statement and, when the specified condition was met, we simply fetched all the data from the local storage, placing it as HTML markup inside an unordered list, with the help of which the records entered earlier by the user are displayed.

    If you test your simplest application, you will find that after reloading the page, everything stays in place. And now, the last thing that remains for us to do is create a function with which the user can delete all his records if necessary. This is accomplished by clearing localStorage and reloading the page to activate the changes made. Next, we, as in the previous case, set false as the return value of the function, which prevents the hash from appearing in the URL. ( * and does not scroll up the page.):

    // Full cleanup localStorage
    window.localStorage.clear ();
    location.reload ();
    return false;
    });

    As a result, we have a fully functioning application. And putting all the above snippets together, we get the complete application code:

    $ ("# add"). click (function () (
    var Description = $ ("# description"). val ();
    if ($ ("# description"). val () == "") (
    $ ("# alert"). html (" Attention! Enter entry in
    text field.");
    $ ("# alert"). fadeIn (). delay (1000) .fadeOut ();
    return false;
    }
    $ ("# todos"). prepend ("

  • "
    + Description + "
  • ");
    $ ("# form"). reset ();
    var todos = $ ("# todos"). html ();
    localStorage.setItem ("todos", todos);
    return false;
    });

    if (localStorage.getItem ("todos")) (
    $ ("# todos"). html (localStorage.getItem ("todos"));
    }

    $ ("# clear"). click (function () (
    window.localStorage.clear ();
    location.reload ();
    return false;
    });

    Browser support.

    The HTML5 specification provides quite powerful support for Web Storage technology, so that it is also implemented by most popular browsers, even IE8. IE7 remains the only problem if you're still interested.

    Conclusion.

    In such small applications, the localStorage mechanism can quite successfully replace the use of databases. For storing small amounts of data, it is not necessary to use more sophisticated alternatives.

    * Translator's note.

    Post Views: 475

    Translation: Vlad Merzhevich

    Persistent local storage is one area where client applications take advantage of server applications. For applications like operating system, provides an abstraction layer for storing and retrieving data such as settings or execution status. These values ​​can be stored in the registry, INI files, XML files, or elsewhere depending on platform principles. If your client application needs local storage for more than just a key / value pair, you can insert your own database, come up with your own file format, or any number of other solutions.

    Historically, web applications have had none of these luxuries. Cookies were invented early in the history of the Internet and can be used to permanently store small amounts of data locally. But they have three potential downsides:

    • Cookies are included in every HTTP request, thereby slowing down your web application from unnecessarily transmitting the same data over and over again.
    • Cookies are included in every HTTP request when data is transmitted over the Internet in unencrypted form (even if the entire web application is transmitted over SSL);
    • Cookies are limited to a data size of about 4 KB - enough to slow down your application (see above), but not enough to be useful.

    Here's what we really want:

    • a lot of storage space;
    • work on the client side;
    • take into account page refresh;
    • there is no sending to the server.

    Before HTML5, all attempts to achieve this ultimately failed in various ways.

    A brief history of local storage before HTML5

    In the beginning, there was only one Internet Explorer. At least Microsoft wanted the world to think so. To this end, within the framework of the First The great war browsers Microsoft has invented so many things and incorporated them into its browser-which-ended-the-war - Internet Explorer. One of these things was called DHTML Behaviors, and one of the behaviors is called userData.

    UserData allows a web page to store up to 64KB of data per domain in a hierarchical XML-like structure. Trusted domains such as intranet sites can store ten times as much. And hey, 640 KB should be enough for everyone. IE has not provided any way to change these conventions, so there is no way to increase the amount of available memory.

    In 2002, Adobe introduced a feature in Flash 6, which turned out to be unfortunate and with a misleading name - "Flash Cookies." In the Flash environment, this capability is better known as Local Shared Objects (LSOs). In short, it allows Flash objects to store up to 100KB of data per domain. Brad Neuberg, who developed an early prototype of the bridge between Flash and JavaScript, called it AMASS (AJAX Massive Storage System), but it was limited by some quirks of Flash design. By 2006, with the introduction of ExternalInterface in Flash 8, accessing LSOs via JavaScript has become an order of magnitude easier and faster. Brad rewrote AMASS and integrated it into the popular Dojo Toolkit under the alias dojox.storage. Flash "free" gives each domain 100kb of storage. In addition, it prompts the user to increase the storage capacity by an order of magnitude upon request (1 MB, 10 MB, etc.).

    if (Modernizr.localstorage) (
    // window.localStorage is available!
    ) else (
    // no native support for HTML5 storage
    }

    Using HTML5 storage

    HTML5 storage is based on the names of key / value pairs. You store information based on the key name, and then you can retrieve that data with the same key. The key name is a string. Data can be any type that JavaScript supports, including strings, booleans, integers, or floating point numbers. However, in reality, the data is stored as a string. If you are saving and retrieving non-strings, you will need to use functions such as parseInt () or parseFloat () to translate the resulting data into valid JavaScript types.

    Storage interface (
    Get it via getItem (key);
    Set via setItem (key, data);
    };

    Calling setItem () with an existing key name will silently overwrite the previous value. Calling getItem () with a non-existent key will return NULL rather than throwing an exception.

    Like other JavaScript objects, you can refer to the localStorage object as an associative array. Instead of using the getItem () and setItem () methods, you can simply specify square brackets... For example this piece of code

    var foo = localStorage.getItem ("bar");
    // ...
    localStorage.setItem ("bar", foo);

    can be rewritten using square brackets syntax:

    var foo = localStorage ["bar"];
    // ...
    localStorage ["bar"] = foo;

    There are also methods for deleting values ​​by key name, as well as clearing the entire store (that is, deleting all keys and values ​​at the same time).

    Storage interface (
    Remove via removeItem (key);
    clear ();
    }

    Calling removeItem () with a non-existent key will return nothing.

    Finally, there is a property for getting the total number of values ​​in the storage area and for iterating over all keys by index (gets the name of each key).

    Storage interface (
    length
    Get key (non-negative integer);
    }

    If, when calling key (), the index is not in the range from 0 to (length-1), then the function will return null.

    Tracking the HTML5 storage area

    If you want to programmatically track storage changes, you must catch the storage event. This event fires on the window object when setItem (), removeItem (), or clear () is called and changes something. For example, if you set an existing value or call clear () when there are no keys, then the event will not fire because the storage area has not really changed.

    The storage event is supported wherever the localStorage object works, including Internet Explorer 8. IE 8 does not support the W3C addEventListener standard (although it will finally be added in IE 9), so to catch the storage event you need to check which event engine supports browser (if you've done this before with other events, you can skip this section to the end). Intercepting the storage event works in the same way as intercepting other events. If you prefer to use jQuery or some other JavaScript library to register event handlers, you can do this with storage too.

    if (window.addEventListener) (
    window.addEventListener ("storage", handle_storage, false);
    ) else (
    window.attachEvent ("onstorage", handle_storage);
    };

    The handle_storage callback will be called with the StorageEvent object, except in Internet Explorer, where events are stored in window.event.

    function handle_storage (e) (
    if (! e) (e = window.event;)
    }

    In this case, e will be a StorageEvent object that has the following useful properties.

    * Note: the url property was originally called uri and some browsers supported this property prior to the specification change. For maximum compatibility, you should check if the url property exists, and if not, check the uri property instead.

    The storage event cannot be canceled, there is no way to stop the change inside the handle_storage callback. It's just the browser's way of telling you, “Hey, this just happened. There is nothing you can do, I just wanted you to know. "

    Limitations in current browsers

    When talking about the history of local storage with third party plugins, I mentioned the limitations of each technique. I remembered that I hadn't said anything about the limitations of the now standard HTML5 storage. I will give you the answers and then I will explain them. The answers, in order of importance, are “5 megabytes”, “QUOTA_EXCEEDED_ERR”, and “no”.

    "5 megabytes" - how much storage space is provided by default. This meaning is surprisingly the same across all browsers, although it is phrased as nothing more than a proposal in the HTML5 spec. You need to understand that you are storing strings, not data in its original format. If you store a lot of integers or floating point numbers, the difference in representation can be large. Each digit in a floating point number is stored as a character and not in the usual representation for such numbers.

    "QUOTA_EXCEEDED_ERR" is the exception you get if you exceed your 5MB quota. "No" is the answer to the next obvious question: "Can I ask the user for more storage space?" At the time of writing, browsers have not implemented any mechanism for web developers to request more storage space. Some browsers (like Opera) allow the user to control storage quotas for each site, but this is purely a user initiative and not something that you, as a developer, can embed in your web application.

    HTML5 storage in action

    Let's take a look at HTML5 storage in action. Let's go back to the one we built in the drawing chapter. There is a small problem with this game: if you close the browser window in the middle of the game, you will lose results. But with HTML5 storage, we can keep the gameplay in place, in the browser itself. Open the demo, take a few moves, close the browser tab, and then reopen it. If your browser supports HTML5 storage, the demo page will magically remember the exact position in the game, including how many moves you made, the position of each piece on the board, and even the selected piece.

    How it works? Every time there is a change in the game, we will call this function.

    function saveGameState () (

    localStorage ["halma.game.in.progress"] = gGameInProgress;
    for (var i = 0; i< kNumPieces; i++) {
    localStorage ["halma.piece." + i + ".row"] = gPieces [i] .row;
    localStorage ["halma.piece." + i + ".column"] = gPieces [i] .column;
    }
    localStorage ["halma.selectedpiece"] = gSelectedPieceIndex;
    localStorage ["halma.selectedpiecehasmoved"] = gSelectedPieceHasMoved;
    localStorage ["halma.movecount"] = gMoveCount;
    return true;
    }

    As you can see, the localStorage object is used to save the game process (gGameInProgress, boolean). Next, all the tokens (gPieces, JavaScript array) are iterated over and a row and column are stored for each of them. After that, some additional game states are saved, including the selected piece (gSelectedPieceIndex, integer), the piece that is in the middle of a long series of jumps (gSelectedPieceHasMoved, boolean) and the total number of moves made (gMoveCount, integer).

    When the page loads, instead of automatically calling the newGame () function, which would return all variables to their original values, we call resumeGame (). The resumeGame () function uses HTML5 storage to check the state of the game in the local storage. If present, it restores the values ​​using the localStorage object.

    function resumeGame () (
    if (! supportsLocalStorage ()) (return false;)
    gGameInProgress = (localStorage ["halma.game.in.progress"] == "true");
    if (! gGameInProgress) (return false;)
    gPieces = new Array (kNumPieces);
    for (var i = 0; i< kNumPieces; i++) {
    var row = parseInt (localStorage ["halma.piece." + i + ".row"]);
    var column = parseInt (localStorage ["halma.piece." + i + ".column"]);
    gPieces [i] = new Cell (row, column);
    }
    gNumPieces = kNumPieces;
    gSelectedPieceIndex = parseInt (localStorage ["halma.selectedpiece"]);
    gSelectedPieceHasMoved = localStorage ["halma.selectedpiecehasmoved"] == "true";
    gMoveCount = parseInt (localStorage ["halma.movecount"]);
    drawBoard ();
    return true;
    }

    The most important part of this function is the caveat that I mentioned earlier in this chapter and will repeat here: data is stored as strings. If you are storing something other than strings, you need to convert them on receipt. For example, the flag that the game is in progress (gGameInProgress) is a boolean type. In the saveGameState () function, we just store it and don't worry about the data type.

    localStorage ["halma.game.in.progress"] = gGameInProgress;

    But in resumeGame (), we have to look at the value we got from local storage as a string and manually construct our own boolean.

    gGameInProgress = (localStorage ["halma.game.in.progress"] == "true");

    Likewise, the number of moves is stored in gMoveCount as an integer, in the saveGameState () function we simply save it.

    localStorage ["halma.movecount"] = gMoveCount;

    But in resumeGame (), we have to convert the value to an integer using JavaScript's built-in parseInt () function.

    gMoveCount = parseInt (localStorage ["halma.movecount"]);

    Beyond Key / Value Pair: Competitive Vision

    While there have been many tricks and workarounds in history, the current state of HTML5 storage is surprisingly good. The new API has been standardized and included in all major browsers, platforms and devices. For a web developer you don't see this every day, right? But that's more than "5 megabytes of key / value pairs" and the future of persistent local storage is ... how to say ... well, let it be a competitive vision.

    One vision is an acronym you already know - SQL. In 2007, Google launched Gears, a cross-browser plugin with open source source code which includes an embedded SQLite based database. This early prototype later influenced the creation of the Web SQL Database specification. Web SQL Database (formerly known as "WebDB") provides a thin wrapper around the database SQL data, which allows you to do the following things from JavaScript:

    openDatabase ("documents", "1.0", "Local document storage", 5 * 1024 * 1024, function (db) (
    db.changeVersion ("", "1.0", function (t) (
    t.executeSql ("CREATE TABLE docids (id, name)");
    ), error);
    });

    As you can see, most of the action is on the line with the ExecuteSQL method. This string can support any SQL command, including SELECT, UPDATE, INSERT, and DELETE. It's like server-side database programming, except that you do it with JavaScript! Oh joy!

    The Web SQL Database specification has been implemented across four browsers and platforms.

    Web SQL Database Support
    IE Firefox Safari Chrome Opera iPhone Android
    4.0+ 4.0+ 10.5+ 3.0+ 2.0+

    Of course, if you've used more than one database in your life, then you know that "SQL" is more of a marketing term than a hard and fast standard (someone might say the same about HTML5, but that doesn't matter). Of course, there is an up-to-date SQL specification (called SQL-92), but there is no database server in the world that only conforms to this specification. There is Oracle SQL, Microsoft SQL, SQL in MySQL, SQL in PostgreSQL, SQL in SQLite. In fact, each of these products adds new ones over time. SQL functions, so even saying "SQL in SQLite" is not enough. You must say "the version of SQL that comes with the SQLite version X.Y.Z".

    All of this brings us to the next caveat, currently at the top of the Web SQL specification.

    The spec is at an impasse: all interested developers are using server-side SQL (SQLite), but we need multiple independent implementations to move towards standardization. While other developers are interested in implementing this specification, the SQL dialect description has been left as a regular reference to Sqlite, which is not acceptable to the standard.

    It is against this backdrop that I will share with you another competitive vision for advanced, persistent local storage for web applications: the Indexed Database API, formerly known as “WebSimpleDB,” now affectionately called IndexedDB.

    The Indexed Database API provides what is called object storage, with a lot of ideas borrowed from SQL databases. There are “databases” with “records”, each record has a certain number of “fields”. Each field has a specific data type that is defined when the database is created. You can select part of the records, then list them with the "cursor". Changes to object storage are processed with "transactions".

    If you've ever programmed SQL databases, these terms are probably familiar to you. The main difference is that object storage does not have a structured query language. You don't write a condition like "SELECT * from USERS where ACTIVE =" Y "". Instead, it uses the methods provided by the object store to open the USERS database, enumerate the records, filter our records, and use accessor methods to get the value of each field of the remaining records. An early walk-through of IndexedDB is a good guide on how IndexedDB works and comparing IndexedDB to Web SQL.

    At the time of writing, IndexedDB has only been implemented in the beta version of Firefox 4. In contrast, Mozilla has stated that it will never implement Web SQL. Google said they are considering IndexedDB support for Chromium and Google chrome... And even Microsoft says IndexedDB is "great for the web."

    What can you do as a web developer with IndexedDB? On this moment practically nothing other than some technology demonstrations. In a year? Perhaps.