Local data storage. Working with local storage in JavaScript. What should you do next?

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.

I sent you an article with a story about HTML5 LocalStorage in browsers. We give him the floor.

I tried to write the simplest and most understandable guide to using localStorage technology. The article turned out to be quite short, due to the fact that the technology itself and the means of working with it are not complicated. To get started, you just need to know a little JavaScript. So, spend 10 minutes on this article and you can safely add the line “I can work with localStorage” to your resume.

What is localStorage?

This is what a JavaScript object looks like:

Var myCar = ( wheels: 4, doors: 4, engine: 1, name: "Jaguar" )

And this is what JSON looks like. Almost the same as a regular js object, only all properties must be enclosed in quotes.

( "firstName": "Ivan", "lastName": "Ivanov", "address": ( "streetAddress": "Moskovskoe sh., 101, apt. 101", "city": "Leningrad", "postalCode": 101101 ), "phoneNumbers": [ "812 123-1234", "916 123-4567" ] )

To understand what localStorage is, just imagine that you have such an object built into your browser somewhere that we can use. At the same time, this object does not clear the values ​​that we write there if we reload the page or even completely close the browser.

In JavaScript terms, localStorage is a property of the global browser object (window). It can be accessed as window.localStorage or simply localStorage.

It’s also worth saying that the browser has a localStorage clone called sessionStorage. Their only difference is that the latter stores data only for one tab (session) and will simply clear its space as soon as we close the tab

Let's look at it live. For example, in Google Chrome you need to open DevTools (F12), go to the “Resources” tab and in the left panel you will see localStorage for this domain and all the values ​​that it contains.

By the way, you should know how localStorage works with domains. For each domain, your browser creates its own localStorage object, and it can only be edited or viewed on that domain. For example, the mydomain-1.com domain cannot access the localStorage of your mydomain-2.com .

Why do I need localStorage?

LocalStorage is needed for only one thing - to store certain data between user sessions. You can think of a thousand and one things that can be stored in the browser's local storage. For example, browser games that use it as a save file, or record the moment at which the user stopped while watching a video, various data for forms, etc.

How do I get started with localStorage?

Very simple.

Working with localStorage is very similar to working with objects in JavaScript. There are several methods for working with it.

localStorage.setItem("key", "value")

Method that adds to localStorage new key with a value (and if such a key already exists, it overwrites it with a new value). We write, for example, localStorage.setItem('myKey', 'myValue');

localStorage.getItem("key")

We take a specific value from the key storage.

localStorage.removeItem("Key")

Removing the key

localStorage.clear()

Clearing all storage

Now you can open the localStorage tab in your browser and practice recording and retrieving data from this storage yourself. If anything happens, we write all the code in a js file.

//Add or change the value: localStorage.setItem("myKey", "myValue"); //now you have the key "myKey" with the value "myValue" stored in localStorage //Output it to the console: var localValue = localStorage.getItem("myKey"); console.log(localValue); //"myValue" //remove: localStorage.removeItem("myKey"); //clear the entire storage localStorage.clear() The same thing, only with square brackets: localStorage["Key"] = "Value" //setting the value localStorage["Key"] //Getting the value delete localStorage["Key"] // Remove value

I would also like to note that localStorage works great with nested structures, for example, objects.

//create an object var obj = ( item1: 1, item2: , item3:"hello" ); var serialObj = JSON.stringify(obj); //serialize it localStorage.setItem("myKey", serialObj); //write it to the storage using the key "myKey" var returnObj = JSON.parse(localStorage.getItem("myKey")) //parse it back as an object

You should also know that browsers allocate 5MB for localStorage. And if you exceed it, you will receive a QUOTA_EXCEEDED_ERR exception. By the way, you can use it to check whether there is still space in your storage.

Try ( localStorage.setItem("key", "value"); ) catch (e) ( if (e == QUOTA_EXCEEDED_ERR) ( alert("Limit exceeded"); ) )

Instead of a conclusion

I would like the developers to draw a simple conclusion from this short article: this technology can already be used in full on your projects. It has good standardization and excellent support, which only develops over time.

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 Flash environment this capability is more properly known as Local Shared Objects (LSO). 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 installed existing value or called clear() when there are no keys, 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, integer), the piece that is in the middle of a long series of jumps (gSelectedPieceHasMoved, boolean), and total number 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 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 must convert the value to an integer using JavaScript's built-in parseInt() function.

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, an open-source cross-browser plugin that includes a built-in 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 in the line with the ExecuteSQL method. This string can support any SQL command, including SELECT, UPDATE, INSERT, and DELETE. It's just like that server programming databases, 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 in MySQL, SQL in PostgreSQL, SQL in 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? At the moment, almost nothing except some technology demonstrations. In a year? Maybe.

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

Getting to know the basics of JavaScript programming often begins with creating simple applications, such as the electronic notebook we use to record things and events that we might forget about. But such applications are characterized by one problem - after the page is reloaded, the list of all previously left entries disappears, that is, the application returns to its original state.

There is a very simple way out of this situation, which involves using the local storage mechanism localStorage. Thanks to the fact that localStorage allows us to save the necessary data on the user's computer, the list of scheduled to-dos and events mentioned above will still be available after a page reload, in addition, localStorage is surprisingly very in a simple way storing data and accessing it when necessary.

What is localStorage?

This is a local data storage mechanism that is part of the Web Storage technology provided by the HTML5 specification. There are two data storage options allowed by this specification:

  • Local storage: allows you to save information without restrictions on storage periods. It is this option that we will use, since the list of tasks in our example must 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 opens it again, all information necessary for further operation of the application will be deleted.

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

HTML

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

  • Field for entering new entries (events, to-dos, etc.).
  • Button to confirm the entered entry.
  • A button to clear an already created to-do list.
  • An unordered list that will be replenished with elements in the form of new entries.
  • And finally, we need div block as a container containing messages displayed to the user, such as, for example, a warning that he forgot to enter the value of the next entry, leaving the input field empty.

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








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

JavaScript

Given the structure of the simple notepad application in our example, the first thing we need to do is provide tracking for the button click event "Add a note" and check whether any information is entered into the text field for the entry, that is, at the moment the button is pressed, it should not be empty. Something like this:

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

This is what we do with this piece of code. When the button is pressed "Add a note" we check if the user has entered anything into the field for new entry. If he did not do this, then the div we provided for displaying messages appears, informing the user that the entry field for the entry is not filled in 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 entry.

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

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

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

    return false;
    });

    As you may have noticed, there is nothing unusual here, the standard version of jQuery code is used. Where we access the localStorage object, we must specify the data we are storing in key/value form. You can use an arbitrary name for the key, and I named it "todos", then we need to indicate what we actually need to store in memory. In this case, it is a complete fragment of HTML markup included in an unordered list (located between the tags), with the help of which all entries previously entered by the user are displayed. From the code you can see that we simply extract the fragment we need using the jQuery .html() method and at the end, having completed everything necessary actions, we set the function's return value 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 further normal operation of the application, we need to check whether localStorage contains information previously saved on the computer and, if so, display it for the user. Since our key name is "todos", we should check for its existence like this:

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

    }

    To check for data availability, we used a regular if statement and, if the condition we specified was met, we simply retrieved all the data from local storage, placing it as HTML markup inside an unordered list, which displays the entries previously entered by the user.

    If you check the operation of your simple application, you will find that after reloading the page everything remains in place. And now, the last thing we need to do is create a function with which the user, if necessary, could delete all his entries. This is implemented 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.):

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

    As a result, we have a fully functioning application. And putting all the above fragments together, we get full code applications:

    $("#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, due to which it is also implemented by most popular browsers, even IE8. The only problem remains IE7, if you're still interested.

    Conclusion.

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

    *Translator's note.

    Post Views: 475

    Hi all! In this article we will look at what is localStorage and how to use it.

    Introduction

    LocalStorage- local storage. Those. this is a specially designated place in the browser (something like a small database) where we can write, read and delete some data. In fact, local storage is very similar to COOKIE, but there are differences. So let's talk about them. Cookie very limited. One cookie maybe just 4096 characters, and their number per domain is approximately 30-50 depending on the browser. In local storage we can store 5-10mb or even more for a long time.

    Where to use them

    The biggest difference cookie from localStorage- this is that the first one works with the server, but the second one does not, although this can also be done, but more on that a little later. Use local storage where you do not need close work with the server, but need to store some temporary data. For example, let's imagine that you are creating some kind of web application where a person can go, enter several tasks that he wants to do in a day and delete those that he has already completed. Why do we need a server here? That's right, no reason. This is where it should be used localStorage. A person comes in, enters tasks, they are recorded in a special place in his browser and stored there. When a person logs in again after some time, they will be selected and displayed from there. For example, by clicking on a task, it will be deleted from local storage and, therefore, will no longer be shown to him. Let's move on to how to use it.

    How to use localStorage

    The data is stored in the same way as in cookie - key:value. To add a new value, write this:

    LocalStorage.setItem("key", "value");

    We use localStorage object and his method setItem, where we pass the key and value.

    To get the data, write the following:

    Var value = localStorage.getItem("key");

    As a result, into the variable value will get the value that is stored under the key that we pass to the method getItem.

    Deleting data

    LocalStorage("key"); // will delete data under the passed key
    localStorage.clear(); // completely clear local storage

    To check if local storage is full, you can use the constant QUOTA_EXCEEDED_ERR

    Try (
    localStorage.setItem("key", "value");
    ) catch (e) (
    if (e == QUOTA_EXCEEDED_ERR) (
    alert("Limit exceeded");
    }
    }

    That's all you need to know about localStorage. It is worth saying that in addition to this object there is another one - sessionStorage. It differs only in that it stores data for only one tab, and it will be deleted as soon as the user closes the tab.

    At the beginning of the article I said that local storage created in order to store local data and not communicate with the server, but, however, we still have such an opportunity. I think some might have already guessed how to do this. So, if you need to send some data to the server, then do the following: get the data from local storage, convert it to JSON string and send using technology Ajax. You can also receive them from the server.

    Bottom line

    So use localStorage where you don’t need to communicate with the server, but need to store data locally, in the user’s browser. We have covered everything you need for this in this article. Thank you for your attention and see you soon!