Local storage. LocalStorage on your fingers. HTML5 storage in action

From web applications such as Google Wave, Gmail, etc. we can see that client side data caching is a good idea for most web applications. Think for yourself, for mobile internet volume is very important. Similar queries in 70% of cases (I did not do any calculations, just expressing arguments in percentages is much more solid) return the same data. In addition, you can cache not only the data, but the application itself.

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

Of all the HTML5 spec, client-side local data stores are probably one of the most talked about 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 visits the site and sees latest version a web application that all other users see. However, with the correct use of local storage and timely data updates, these problems can be avoided.

So, client-side storage is divided into 3 principle 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 of the order of several Mbps. Unlike cookies, session data is not sent on every request.
Benefits: When requested, the payload is minimal.
Here's an example of a session storage:

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

2. Local storage - local storage

The LocalStorage JavaScript object is functionally identical to the sessionStorage object. They differ only in life expectancy and scope. Scope: data in localStorage is accessible through 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 shouldn't be sent to the server. Data is available by JavaScript and Flash. This can be very handy for Flash games.

GlobalStorage [""]. Foo \u003d "bar"; // foo will be available on any globalStorage website ["ru"]. foo1 \u003d "bar1"; // foo1 will be available on sites "..foo2 \u003d" bar2 "; // foo2 will only be available 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, the data is retained even after the tab / window / browser is closed.

Here's how you can do it:

LocalStorage.setItem ("userName", "taranfx"); // define a variable in localStorage alert ("Your name is:" + localStorage.getItem ("userName")); // access to 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've discussed key-value-limited stores. But when you are dealing with large amounts of data, better base data haven't come up with anything yet. Browsers use SQLite database, which works without additional processes and servers. With only minor restrictions, for example, no foreign key.

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

Hi everyone! In this article we will analyze 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 COOKIEbut there are differences. Let's talk about them. Cookie very limited. One cookie maybe everything 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 works with the server, and the second does not, although this can also be done, but more on that later. Use local storage where you do not need close work with the server, but you need to store some temporary data. For example, let's say 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, there is nothing. This is where you should use localStorage... A person enters, enters tasks, they are recorded in a special place in his browser and are stored there. When a person enters again after a while, they will be selected and shown from there. For example, clicking on a task will remove it 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 like 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 \u003d 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"); // delete the data under the passed key
localStorage.clear (); // clean up local storage completely

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

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

That's all there is to know about localStorage... It is worth saying that in addition to this object, there is one more - sessionStorage... It differs only in that it stores data for only one tab, and they 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 already have guessed how to do this. So, if you need to send some data to the server, then do the following: get data from local storage, convert it to Json string and send using technology Ajax... You can also receive them from the server.

Outcome

So use localStorage where you do not 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!

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 amongst 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 ExplorerOperaSafariAndroid 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.

Making a to-do list app is usually the first app you make when learning JavaScript, but the problem with all these apps is that when you reload the page, all of those to-do lists disappear.
There is a simple solution - using local storage. The advantage of local storage is that you can save bits of data on the user's computer, and when the page is reloaded, all the task lists remain in place.

What is local storage?

Local storage is part of the storage network, which itself is part of the HTML5 specification. There are two options for storing data in a specification:

  • Local Storage: Stores data without an expiration date, and this is the option we'll use because we want our lists to stay on the page as long as possible.
  • Session Storage: only stores data for one session, so if the user closes the tab and reopens it, all his data will be lost.

In simple words, all that web storage does is store key / value pairs with a name locally, and unlike cookies, this data is saved even if you close your browser or turn off your computer.

If we're thinking about a to-do list, then you need the following:

  • Entrance, where we can place our list
  • Enter button to add a list
  • Button to clear the entire diary
  • An unordered list container where our list will be placed in a list of items
  • Finally, we need a DIV container to show a notification when you try to enter an empty task.

Thus, our HTML should look something like this:

This is a pretty standard HTML container and with our JavaScript we can fill it all up with dynamic content.

Since we will be using JQuery in this example, you must include it in the HTML document as well.

JavaScript

If we think about the structure of a simple “to-do list” application, the first thing we need to do is check if the input is empty when the user clicks on the add or check button:

$ ("# add"). click (function () (var Description \u003d $ ("# description"). val (); // if the to-do is empty if ($ ("# description"). val ( ) \u003d\u003d "") ($ ("# alert"). html (" Warning! You left the to-do empty "); $ (" # alert "). FadeIn (). Delay (1000) .fadeOut (); return false;)

All we did was test a click on the Add button and run a simple test to check if the user has filled in something. If not, then the div warning pops up and stays for 1000ms and then disappears.

The next thing we need to do is insert a list item with a value into the input line, and we will preface this so that when the user adds a task, it will always go to the beginning of the list, and then save the list item to local storage, like this:

// add the list item $ ("# todos"). prepend ("

  • "+ Description +"
  • "); // delete whatever is in the input $ (" # form "). reset (); var todos \u003d $ (" # todos "). html (); localStorage.setItem (" todos ", todos); return false;));

    As you can see, this is pretty standard jQuery and when it comes to local storage we have to store the key and value. The key is the name we give ourselves, in this case we'll just call it “Todos”, then we have to define what we want to store, and in this case it's all the HTML that's inside the Todos unordered list. As you can see, we captured everything from using jQuery, and finally, returned false so that the form would not give up and our page would not be refreshed.

    Our next step is to check if we have something saved on local storage. If so, then we need to place this on the page, given that we gave our key the name “todos”, we need to check for its existence. Like this:

    // if we have something on local storage place that if (localStorage.getItem ("todos")) ($ ("# todos"). html (localStorage.getItem ("todos"));)

    If you test our application and reload the page, you will see that it is already working. All we have to do is create a function that will be responsible for clearing the entire list. We erase all local storage, reload the page for our change to take effect, and then return “false” to prevent the hash before the URL like this:

    // clear all the local storage $ ("# clear"). click (function () (window.localStorage.clear (); location.reload (); return false;));

    The complete code looks like this:

    $ ("# add"). click (function () (var Description \u003d $ ("# description"). val (); if ($ ("# description"). val () \u003d\u003d "") ($ ( "#alert"). html (" Warning! You left the to-do empty "); $ (" # alert "). FadeIn (). Delay (1000) .fadeOut (); return false;) $ (" # todos "). Prepend ("

  • "+ Description +"
  • "); $ (" # form "). reset (); var todos \u003d $ (" # 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

    Web Storage support is pretty good for HTML5 specs, it is supported by all major browsers and even IE8.

    Very often the first JavaScript application is a Todo list, but the problem with such applications is that after refreshing the page, all the list items disappear.

    A simple solution to this problem is to use local storage (Local Storage). Local storage allows you to store data on the user's machine and you can easily load the list from it after refreshing the page. In this article, we will write a small todo-list using local storage.

    What is local storage?

    Local storage ("web storage") was originally part of the HTML5 specification, but has now been moved to a separate one. There are two ways to store data:

    • Local storage: persistent storage, that's what we'll be using.
    • Session storage: stores data for this session only, if the user closes the page, the data will be lost.

    Local storage allows you to store data in the form of key-value pairs on the user's computer, and this data will be available even after the browser is closed or the computer is turned off.

    Html

    To create a todo list, we need:

    • Text input for entering the content of the element.
    • Button for adding an item to the list.
    • Button to clear the list.
    • The list itself (
        ).
      • And an extra div for showing errors.

      Thus, the HTML markup will look like this:

      Quite a simple structure that we'll animate with JavaScript.

      Because we are using jQuery, you need to additionally connect it.

      JavaScript

      First, we need to track the click on the add button and check that the input field is not empty:

      $ ("# add"). click (function () (var Description \u003d $ ("# description"). val (); if ($ ("# description"). val () \u003d\u003d "") ($ ( "#alert"). html (" Warning! You left the to-do empty "); $ (" # alert "). FadeIn (). Delay (1000) .fadeOut (); return false;)

      This code checks the value of the text input and, if it is empty, shows an error and returns false so that the rest of the code is not executed and the element is not added to the list.

      // insert the entry $ ("# todos"). prepend ("

    • "+ Description +"
    • "); // delete whatever is left in the text box $ (" # form "). reset (); var todos \u003d $ (" # todos "). html (); localStorage.setItem (" todos ", todos); return false;));

      To work with local storage, you must provide a key and a corresponding value. In our case, let's call the key ‘todos’, and the value will be all the HTML code contained in the list (in the tag

        ). This code is easy to get with jQuery. Finally, we return false to prevent the form from being submitted and not reloading the page.

        The next step is to check the local storage, if a value with the 'todos' key exists, then load the list from the local storage:

        If (localStorage.getItem ("todos")) ($ ("# todos"). Html (localStorage.getItem ("todos"));)

        Because we store the finished HTML in the repository, then we simply insert this code into the list.

        Our todo-list is almost ready, all that remains is to implement the function to clear the list. When the user clicks on the button, the entire list will be deleted and the local storage will be cleared:

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

        Done! The complete code looks like this:

        $ (document) .ready (function () ($ ("# add"). click (function () (var Description \u003d $ ("# description"). val (); if ($ ("# description"). val () \u003d\u003d "") ($ ("# alert"). html (" Warning! You left the to-do empty "); $ (" # alert "). FadeIn (). Delay (1000) .fadeOut (); return false;) $ (" # todos "). Prepend ("

      • "+ Description +"
      • "); $ (" # form "). reset (); var todos \u003d $ (" # 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

        All major browsers support web storage, even IE8. The only thing to worry about is IE7 and below.

        Conclusion

        Local storage in such small applications can be a great replacement for a database. Storing small amounts of information shouldn't be difficult.