What does local cookie storage mean? How to Use Local Data Storage in JavaScript

From web applications such as Google Wave, Gmail, etc. we see that caching data on the client side is 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 a text file (4KB or 20 key-value pairs maximum (IE) per 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 updating of 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

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 amounts of data, better base The data haven’t come up with anything yet. 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-fledged SQL database. And work with it is carried out in SQL.

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 most big 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!

Very often the first JavaScript application is a Todo list, but the problem with such applications is that after the page is refreshed, 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 download 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 its own. There are two ways to store data:

  • Local Storage: persistent storage, this is what we will use.
  • Session Storage: stores data only for this session, 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 closing the browser or turning off the computer.

HTML

To create a todo list we need:

  • Text input for entering the element's content.
  • Button to add an item to the list.
  • Button to clear the list.
  • The list itself (
      ).
    • And an additional div to show errors.

    Thus HTML markup will look like this:

    Enough simple structure, which we'll bring to life using JavaScript.

    Because we use jQuery, we 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 = $("#description").val(); if($("#description").val() == "") ( $( "#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 does not execute and the element is not added to the list.

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

  • "+Description+"
  • "); // delete everything that is left in the text field $("#form").reset(); var todos = $("#todos").html(); localStorage.setItem("todos", todos); return false; ));

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

      ). This code is easy to get from using jQuery. And finally we return false to prevent the form from being submitted and not reload the page.

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

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

      Because we store ready HTML in the repository, then we simply paste this code into the list.

      Our todo-list is almost ready, all that remains is to implement the list cleaning function. 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; ));

      Ready! The complete code looks like this:

      $(document).ready(function() ( $("#add").click(function() ( var Description = $("#description").val(); if ($("#description"). val() == "") ( $("#alert").html(" Warning! You left the to-do empty"); $("#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

      Web storage is supported by all major browsers, even IE8. You should only be wary of IE7 and below.

      Conclusion

      Local storage in such small applications can be an excellent replacement for a database. Storing small amounts of information should not be difficult.

      Storing data directly in the browser has many advantages, the main one being fast and network-independent access to the “database”. On this moment There are 4 active methods for this (plus one deprecated):

      1. Local storage
      2. Session storage
      3. IndexedDB
      4. WebSQL (deprecated)

      Cookies

      Cookies are a classic way of storing simple string data within a document. Typically, cookies are sent from the server to the client, which can store them and then send them back to the server in response to subsequent requests. This can be used for things like managing account sessions or tracking user information.

      Additionally, cookies can be used to easy storage data on client side. Therefore, they are also often used to store general data such as user settings.

      Basic CRUD operations with cookies

      // Create document.cookie = "user_name=Ire Aderinokun"; document.cookie = "user_age=25;max-age=31536000;secure"; // Read (All) console.log(document.cookie); // Update document.cookie = "user_age=24;max-age=31536000;secure"; // Delete document.cookie = "user_name=Ire Aderinokun;expires=Thu, 01 Jan 1970 00:00:01 GMT";

      Benefits of cookies

      • They can be used to communicate with the server
      • We can set cookies to automatically expire instead of manually deleting them.

      Disadvantages of cookies

      • They are added to the loading of the document page
      • They can store a small amount of data
      • They can only contain strings.
      • Potential security issues.
      • This method has not been recommended for storing data on the client since the advent of the Web Storage API (local and session storage).

      Browser support

      Cookies have basic support in all big browsers.

      Local storage

      Local storage is a subset of the Web Storage API, a special API for storing data in the browser in a key-value format. This API was created as a solution to cookie problems and is more intuitive and in a safe way storing simple data inside the browser.

      Although technically we can only store strings in local storage, this is overcome by converting to JSON. This way we can store more complex data in local storage compared to cookies.

      Basic CRUD operations with local storage

      // Create const user = ( name: "Ire Aderinokun", age: 25 ) localStorage.setItem("user", JSON.stringify(user)); // Read (Single) console.log(JSON.parse(localStorage.getItem("user"))) // Update const updatedUser = ( name: "Ire Aderinokun", age: 24 ) localStorage.setItem("user", JSON.stringify(updatedUser)); // Delete localStorage.removeItem("user");

      Benefits of Local Storage

      • Offers a simpler and more intuitive data storage interface.
      • More secure for storing data on the client.
      • Allows you to store more data (all 3 points - compared to cookies).

      Disadvantages of Local Storage

      • Allows you to store only strings

      Browser support

      Session storage

      Session storage is the second type of Web Storage API. It is exactly the same as local storage except that the data is stored only for the browser tab session. As soon as the user navigates away from the page and closes the browser, the data is cleared.

      Basic CRUD operations with session storage

      // Create const user = ( name: "Ire Aderinokun", age: 25 ) sessionStorage.setItem("user", JSON.stringify(user)); // Read (Single) console.log(JSON.parse(sessionStorage.getItem("user"))) // Update const updatedUser = ( name: "Ire Aderinokun", age: 24 ) sessionStorage.setItem("user", JSON.stringify(updatedUser)); // Delete sessionStorage.removeItem("user");

      The advantages, disadvantages and support in browsers are exactly the same as for local storage.

      IndexedDB

      IndexedDB is a much more complex and mature solution for storing data in the browser, as it is a low-level API for storing significant amounts of structured data on the client. At its core, it is an object-oriented database based on JavaScript that allows us to easily store and retrieve data indexed by key.

      WebSQL

      WebSQL is a client-side relational database API similar to SQLite. Since 2010 working group The W3C has discontinued work on this specification and this API is no longer part of the HTML specification and should not be used.

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

      Internet