Local storage. LocalStorage. Local storage in HTML5. A Brief History of Local Storage Before HTML5

The Web Storage API provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.

Web Storage concepts and usage

The two mechanisms within Web Storage are as follows:

  • sessionStorage maintains a separate storage area for each given origin that"s available for the duration of the page session (as long as the browser is open, including page reloads and restores)
    • Stores data only for a session, meaning that the data is stored until the browser (or tab) is closed.
    • Data is never transferred to the server.
    • Storage limit is larger than a cookie (at most 5MB).
  • localStorage does the same thing, but persists even when the browser is closed and reopened.
    • Stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser cache / Locally Stored Data.
    • Storage limit is the maximum among the three.

Specifications

Specification Status Comment
HTML Living Standard Living Standard

Browser compatibility

Window.localStorage

https://github.com/mdn/browser-compat-data and send us a pull request.

DesktopMobile
ChromeEdgeFirefoxInternet Explorer OperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
localStorageChrome Full support 4Edge Full support 12Firefox Full support 3.5IE Full support 8Opera Full support 10.5Safari Full support 4

Legend

Full support Full support

Window.sessionStorage

The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
sessionStorageChrome Full support 5Edge Full support 12Firefox Full support 2IE Full support 8Opera Full support 10.5Safari Full support 4WebView Android Full support YesChrome Android Full support YesFirefox Android Full support YesOpera Android Full support 11Safari iOS Full support 3.2Samsung Internet Android Full support Yes

Legend

Full support Full support

Private Browsing / Incognito modes

Most modern browsers support a privacy option called "Incognito", "Private Browsing" or something similar that doesn't store data like history and cookies. This is fundamentally incompatible with Web Storage for obvious reasons. As such, browser vendors are experimenting with different scenarios for how to deal with this incompatibility.

Most browsers have opted for a strategy where storage APIs are still available and seemingly fully functional, with the one big difference that all stored data is wiped after the browser is closed. For these browsers there are still different interpretations of what should be done with existing stored data (from a regular browsing session). Should it be available to read when in Private mode? Then there are some browsers, most notably Safari, that have opted for a solution where storage is available, but is empty and has a quota of 0 bytes assigned, effectively making it impossible to write data to it.

Developers should be aware of these different implementations and take them into account when developing websites depending on Web Storage APIs. For more information please have a look at this WHATWG blog post that specifically deals with this topic.

Of such web applications, like Google Wave, Gmail, etc. We see that client-side data caching is a good idea for most web applications. Think for yourself, for mobile internet volume is very important. Queries of the same type in 70% of cases (I didn’t do any calculations, it’s just much more solid to express the arguments as percentages) return the same data. In addition, you can cache not only data, but also the application itself.

Until now, the most popular method for local storage has been cookies. A cookie is a key-value pair that is stored locally in text file(4KB or 20 key-value pairs maximum (IE) for one domain). In addition, cookies are sent to the server with any HTTP request to the server, even with AJAX. It is natural that the standard should have included means for more practical storage of data in the browser.

Of the entire HTML5 specification, local client-side data storage is probably one of the most discussed topics. There are both positive and negative opinions. Of the minuses, the most significant is a violation of the concept of data relevance for all users, i.e. the way it works now: the user goes to the site and sees latest version web application, the one that all other users see. However, with the correct use of local storage and timely updates data, these problems can be avoided.

So, client-side storage is divided into 3 fundamental methodologies:

  1. Session storage.
  2. Local storage or Global Storage

Let's take a closer look at each of them:

1. Session Storage- session storage

Session storage is more convenient than cookies. With different implementations max. the limit can be on the order of several Mbits. Unlike cookies, session data is not sent with every request.
Advantages: When requested, the payload is minimal.
Here is an example of a session storage:

SessionStorage.setItem("userName", "taranfx"); // define the session variable alert("Your name is: " + sessionStorage.getItem("userName")); // access check alert("Hello " + sessionStorage.userName); // another method of accessing the session variable sessionStorage.removeItem("userName"); // at the end we delete the variable

2. Local Storage- local storage

The LocalStorage JavaScript object is functionally identical to the sessionStorage object. They differ only in life expectancy and visibility. Scope: data in localStorage is accessible across all browser windows, while sessionStorage data is limited to the window in which it was created.
Global memory storage is set by the browser, websites can use it to store persistent data that does not need to be sent to the server. Data is available via JavaScript and Flash. This can be very convenient for Flash games.

GlobalStorage[""].foo = "bar"; // foo will be available on any website globalStorage["ru"].foo1 = "bar1"; // foo1 will be available on sites "..foo2 = "bar2"; // foo2 will be available only on the site

When storing data locally, the specification has been rewritten to be more secure. Those. Now the data is automatically linked to the domain.
Duration of validity: When stored in Local Storage, data is retained even after closing the tab/window/browser.

Here's how to do it:

LocalStorage.setItem("userName", "taranfx"); // define a variable in localStorage alert("Your name is: " + localStorage.getItem("userName")); // access it alert("Hello " + localStorage.userName); // access it differently localStorage.removeItem("userName"); // delete it at the end

3. Database Storage- storage in a database

So far we have discussed stores limited to key-value pairs. But when you are dealing with large volumes of data, nothing better than a database has yet been invented. Browsers use SQLite database, which works without additional processes and servers. Only with minor restrictions, for example the absence of a foreign key.

But as a reward you get a full SQL database data. And work with it is carried out in SQL.

The cookies that we discussed in the previous lesson are very limited: one cookie can only have 4096 characters, and the number of cookies per domain can be approximately 30-50, depending on the browser.

Therefore, alas, it will not be possible to store a lot of information there. This is how it 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 designed to work with local storage. It has 4 easy to understand methods. Here they are://Saving the value: localStorage.setItem("Key", "Value"); //Getting the value: var value = localStorage.getItem("Key"); //Removing a value: localStorage.removeItem("Key"); //Clearing the entire storage: localStorage.clear();

WITH

localStorage It has 4 easy to understand methods. Here they are: you can also work as with a regular array: //Saving the value: localStorage["Key"] = "Value"; //Getting the value: var value = localStorage["Key"]; //Deleting a value: delete localStorage["Key"]; Apart from the object

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 tab with the site.

Well, localStorage stores data for a long time until this data is deleted by the script, or the browser user clears the local storage using the settings.

Examples

IN

following example

we will write the username to local storage:

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 will get a string that can already be saved in localStorage.

Then, when we need to get this object back, we convert the string from JSON back into an object - and calmly use it.

Let's look at this process with an example. Let's 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 key obj: localStorage.setItem("obj", json);

After some time we get the object back:

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

Additional features

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

Determining the name of a 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 an Event object with the following properties will be available in it:

function func(event) ( var key = event.key; //changeable data key 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 should you do next:

playlist on YouTube

Practical Application of ES6

Some videos may get ahead of themselves, as we haven’t covered all of ES6 yet at this point in the tutorial. Just skip these videos and watch them later.

The right place to store confidential and important data is a web server. For example, if you add items to your shopping cart in an online store, data about your potential purchase is stored on a web server. Only a few bytes of tracking data containing information about you (or rather, about your computer) are stored on your computer so that the web server knows which cart is yours. Even with the new features 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, because... Sometimes it is easier to store non-essential information on the user's computer. For example, it makes sense to store locally custom settings(say, settings that determine how a web page is displayed) and application state (a snapshot of the current state of the web application) so that the visitor can continue running it from the same point later.

Before HTML5 the only way local data storage 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 a bit clunky. The cookie system also forces the developer to fiddle with expiration dates and needlessly send data back and forth across the Internet with each page request.

In HTML5 it is entered best alternative cookies, which allows you to easily and simply store information on the visitor’s computer. This information can be stored on the client's computer indefinitely, is not sent to the web server (unless the developer does so), can be large in size, and requires only a couple of simple, efficient JavaScript objects to manipulate.

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

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

Information stored in web storage is not actually stored on the Internet, but on the computer of the web page visitor. In other words, web storage means storing data not on the Internet, but storing data from the Internet.

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

Local storage

Uses object It has 4 easy to understand methods. Here they are: to store data for the entire website on a permanent basis. This means that if a web page stores data in local storage, that data will be available to the user when he returns 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. Some browsers implement this as an all-or-nothing strategy and delete all local data, much like cookies are deleted. (In fact, in some browsers, the cookie system and local storage are interconnected, so the only way to delete local data is to delete the cookies.) And other browsers may allow the user to view data for each individual website and delete data for a selected site or sites.

Session data storage

Uses object //Saving the value: localStorage["Key"] = "Value"; //Getting the value: var value = localStorage["Key"]; //Deleting a value: delete localStorage["Key"]; for temporary storage of data for one browser window or tab. This data is only available until the user closes the window or tab, after which the session ends and the data is deleted. But session data is retained if the user goes to another website and then returns again, as long as it happens in the same browser window.

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

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

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

In addition, because 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 information that it has stored on another computer. Likewise, a web page creates separate local storage if you log in with a different username or run a different browser.

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

For storing large amounts of data, a still evolving database standard IndexedDB allows local storage of much larger amounts - usually 50 MB to start with and more if the user agrees.

Saving data

Before a piece of information can be placed in local or session storage, it must be given 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 piece of data is as follows:

localStorage = data;

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

Of course, saving a fragment of static text does not make sense. Typically we need to store some variable data, for example current date, the result of a mathematical calculation or text data entered by the user into form fields. The following is an example of saving user-entered text data:

Web storage

Function saveData() ( // Get the values ​​of the text fields var localData = document.getElementById("localData").value; var sessionData = document.getElementById("sessionData").value; // Save the text entered in the text field into local storage localStorage["localData"] = localData; // Save the text entered in the text field to the session storage sessionStorage["sessionData"] = sessionData; function loadData() ( // Load saved data from storage 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 fields: for local storage (at the top) and for session storage (at the bottom). Clicking the "Save" button saves the text entered in 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 rather than localStorage["username"]. Both types of syntax are equivalent, and using one or the other is a matter of personal preference.

Web storage doesn't work without a web server

In your web storage research, you may encounter an unexpected problem. In many browsers, web storage only works for pages provided by the web server. It doesn’t matter where the server is located, on the Internet or on your own computer, the most important thing is simply that the pages are not launched from the local hard drive(for example, by double-clicking the page file icon).

This feature is a side effect of the way browsers allocate local storage space. As previously stated, browsers limit per-website local storage to 5MB, which requires them to associate each page that wants to use local storage with the website's domain.

So what happens if you open a page that uses web storage from your local hard drive? It all depends on the browser. Internet Browser Explorer appears to be losing web storage support entirely. The localStorage and sessionStorage objects disappear and attempting to use them causes a JavaScript error.

sessionStorage Firefox browser the localStorage and sessionStorage objects remain in place and seem to be supported (even Modernizr determines that they are supported), but everything that is sent to storage disappears to God knows where. IN Chrome browser again something different - most of the web storage functionality works as it should, but some capabilities (like the onStorage event) don't work.

Similar problems arise when using the File API. So you'll save yourself a lot of hassle if you put the page you're testing on a test server to avoid all those uncertainties.

Browser support for web storage

Web storage is one of the most supported features of HTML5, 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 storage and session data storage capabilities. But support for the onStorage event requires later versions of browsers, such as IE 9, Firefox 4 or Chrome 6.

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

Translation: Vlad Merzhevich

Persistent local storage is one area where client applications have advantages over server applications. For applications such as operating system, provides an abstraction layer for storing and retrieving data such as settings or execution status. These values ​​may be stored in the registry, INI files, XML files, or elsewhere depending on the principles of the platform. 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 disadvantages:

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

Here's what we really want:

  • plenty of storage space;
  • work on the client side;
  • take into account page refreshes;
  • 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 that's what Microsoft wanted the world to think. To this end, within the framework of the First Great War browsers Microsoft invented a lot of things and included them in its browser-that-ended-the-war, Internet Explorer. One of these things was called DHTML Behaviors, and one of the behaviors was called userData.

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

In 2002, Adobe introduced a feature in Flash 6 that was unsuccessful and misleadingly named “Flash Cookies.” In the Flash environment, this feature is more properly known as Local Shared Objects (LSOs). In short, it allows Flash objects to store up to 100 KB of data per domain. Brad Neuberg, who developed an early prototype of a 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 became an order of magnitude easier and faster. Brad rewrote AMASS and integrated it into the popular Dojo Toolkit under the alias dojox.storage. Flash gives each domain 100kb of storage “for free”. In addition, it offers the user, upon request, to increase the storage volume by an order of magnitude (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 key/value pair names. 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. The 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 storing and retrieving non-strings, you will need to use functions like parseInt() or parseFloat() to convert the received data into the correct JavaScript types.

Storage interface (
Get 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 throw an exception.

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

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

can be rewritten using square bracket 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 once).

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

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

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

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

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

HTML5 Storage Area Monitoring

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

The storage event is supported wherever the localStorage object runs, 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 it browser (if you've done this before with other events, you can skip to the end of this section). 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, the variable e will be a StorageEvent object, which has the following useful properties.

*Note: the url property was originally called uri and some browsers supported this property before the specification changed. To ensure maximum compatibility, you should check whether the url property exists, and if not, check the uri property instead.

The storage event cannot be canceled, and 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's nothing you can do, I just wanted you to know."

Limitations in current browsers

When talking about the history of local storage using third-party plugins, I mentioned the limitations of each technique. I remembered that I didn't say anything about the limitations of the now standard HTML5 storage. I will give you the answers and then explain them. The answers, in order of importance, are "5 megabytes", "QUOTA_EXCEEDED_ERR" and "none".

“5 megabytes” - how much storage space is provided by default. This value is surprisingly consistent across all browsers, although it is stated as nothing more than a suggestion in the HTML5 specification. You need to understand that you are storing strings, not data in the 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, rather than in the usual representation for such numbers.

"QUOTA_EXCEEDED_ERR" is the exception you will receive if you exceed your 5 MB 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 do not implement any mechanism for web developers to request more storage space. Some browsers (such as Opera) allow the user to control storage quotas on a per-site basis, but this is purely a user initiative and unrelated to anything you as a developer can build into your web application.

HTML5 storage in action

Let's take a look at HTML5 storage in action. Let's turn again to the one we built in the chapter on drawing. There is a small problem with this game: if you close the browser window in the middle of the game, you will lose the results. But with HTML5 storage, we can save the game process locally, in the browser itself. Open the demo, make a few moves, close the browser tab, and then open it again. 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 progress (gGameInProgress, boolean type). Next, all the pieces are sorted out (gPieces, JavaScript array) and stores a row and column for each. Some additional game states are then saved, including the selected piece (gSelectedPieceIndex, an integer), the piece that is in the middle of a long series of jumps (gSelectedPieceHasMoved, a boolean), and the total number of moves made (gMoveCount, an 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 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 feature is a caveat that I mentioned earlier in this chapter and will repeat here: data is stored as strings. If you're storing something other than strings, you'll need to convert them when you receive them. For example, the flag that a game is in progress (gGameInProgress) is a Boolean type. In the saveGameState() function we simply store it and don't worry about the data type.

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

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

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

Similarly, 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 the resumeGame() function we have to convert the value to an integer using the built-in JavaScript function parseInt() .

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

Beyond Key/Value Pairs: Competitive Vision

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

One vision is an acronym you already know - SQL. In 2007, Google launched Gears, a cross-browser open-source plugin source code, which includes a built-in SQLite-based database. This early prototype later influenced the creation of the Web SQL Database specification. Base Web data SQL (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 in the line with the ExecuteSQL method. This string can support any SQL command, including SELECT, UPDATE, INSERT, and DELETE. It's just like server-side database programming, except you do it with JavaScript! O joy!

The Web SQL database specification has been implemented in four browsers and platforms.

Web SQL database support
I.E. 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, you know that "SQL" is more of a marketing term than a hard and fast standard (some might say the same about HTML5, but that doesn't matter). Of course, there is a current SQL specification (called SQL-92), but there is no database server in the world that conforms only to this specification. There is Oracle SQL, Microsoft SQL, SQL to MySQL, SQL to PostgreSQL, SQL to SQLite. In fact, each of these products adds new SQL functionality over time, so even saying "SQL in SQLite" is not enough. You should say "version of SQL that comes with SQLite version X.Y.Z".

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

The specification has reached a dead end: all interested developers use 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 mere reference to Sqlite, which is not acceptable for the standard.

It is against this background that I will tell you about another competitive vision for the advanced, persistent local storage for web applications: Indexed Database API, formerly known as "WebSimpleDB", now affectionately called IndexedDB.

The Indexed Database API provides what is called object storage, with many ideas borrowed from SQL databases. There are "databases" with "records", each record having a certain number of "fields". Each field has a specific data type, which is determined when the database is created. You can select a subset of records, then list them with the "cursor". Changes to the object store 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, we use 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 tutorial on how IndexedDB works and how IndexedDB compares to Web SQL.

At the time of writing, IndexedDB has only been implemented in the Firefox 4 beta. By contrast, Mozilla has stated that it will never implement Web SQL. Google has stated that they are considering IndexedDB support for Chromium and Google Chrome. And even Microsoft said that IndexedDB is “a great solution for the web.”

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