Very often, the first JavaScript application is a Todo list, but the problem with such applications is that after refreshing the page, all the items in the list 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. You can store data in two ways:

  • local storage: persistent storage, which is 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 on the user's computer in the form of key-value pairs, 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:

  • A text input to enter the element's content.
  • Button for adding an item to the list.
  • Button to clear the list.
  • The list itself
      ).
    • And an extra div to show errors.

    So the HTML markup will look like this:

    Enough simple structure, which we will bring to life with JavaScript.

    Because we use jQuery, we need to additionally include 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 it 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 entry $("#todos").prepend("

  • " + Description + "
  • "); // delete everything 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 jQuery. And finally we return false to prevent the form from submitting and not reloading 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 just paste this code into the list.

      Our todo-list is almost ready, it remains only to implement the function of clearing 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; ));

      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 afraid of IE7 and below.

      Conclusion

      Local storage in such small applications can become great replacement database. Storing small amounts of information should not be difficult.

      Creating a to-do list app is usually the first app you make when learning JavaScript, but the problem with all those apps is that when you reload the page, all those lists disappear.
      There is a simple solution - using local storage. The advantage of local storage is that you can store bits of data on the user's computer, and when the page reloads, all task lists are left 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 BOM:

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

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

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

      • Entrance, where it will be possible to place our list
      • Enter button to add list
      • Button to clear the entire diary
      • An unordered list container where our list will be put into a list of elements
      • And finally, we need a DIV container to show a notification when you try to enter an empty task.

      So our HTML should look something like this:

      It's a pretty standard HTML container, and with our JavaScript we can populate it all with dynamic content.

      Since we'll be using jQuery in this example, you'll also need to include it in the HTML document.

      JavaScript

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

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

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

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

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

    • " + Description + "
    • "); // delete whatever is in the input $("#form").reset(); var todos = $("#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, which in this case is all the HTML that's inside the Todos of the unordered list. As you can see, we captured everything with jQuery, and finally returned “false” (false) so that the form does not give up and our page does not refresh.

      Our next step is to check if we have something stored locally. If there is, then we need to put it on the page, given that we have given 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 = $("#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 support is pretty good for the HTML5 spec, it's supported by all major browsers and even IE8.

      Translation: Vlad Merzhevich

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

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

      • cookies are included with every HTTP request, thus slowing down your web application by needlessly sending the same data over and over again;
      • cookies are included in every HTTP request when data is transmitted over the Internet in an unencrypted form (even if the entire web application is transmitted over SSL);
      • cookies are limited to about 4 KB 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;
      • consider page refresh;
      • no sending to server.

      Before HTML5, all attempts to achieve this ended up failing in various ways.

      A Brief History of Local Storage Before HTML5

      In the beginning there was only one Internet Explorer. At least Microsoft wanted the world to think so. To that end, as part of the First Great Browser War, Microsoft invented a lot of things and included them in its browser-that-ended-the-war, Internet Explorer. One of these things has been called DHTML Behaviors and one of the behaviors is 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, 640kb should be enough for everyone. IE has not provided any way to change these conventions, so there is no way to increase the available memory.

      In 2002, Adobe introduced a feature in Flash 6 that was unsuccessful and misleadingly named "Flash cookies". In Flash, this feature is known more correctly as Local Shared Objects (local accessible objects, LSOs). In short, it allows Flash objects to store up to 100 KB of data per domain. Brad Neuberg developed an early prototype of a bridge between Flash and JavaScript called it AMASS (AJAX Massive Storage System), but it was limited by some Flash design quirks. By 2006, with the advent of ExternalInterface in Flash 8, accessing the LSO via JavaScript had become an order of magnitude easier and faster. Brad rewrote AMASS and integrated it into the popular Dojo Toolkit under the alias dojox.storage . Flash "free" gives each domain 100 kb of storage. In addition, it prompts the user to increase the amount of storage by an order of magnitude (1 MB, 10 MB, etc.) when requested.

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

      Using HTML5 storage

      HTML5 storage is based on the names of key/value pairs. You store information based on a 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, the data is actually stored as a string. If you are storing and retrieving non-strings, you will need to use functions like parseInt() or parseFloat() to translate 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 others JavaScript objects you can access the localStorage object as an associative array. Instead of using the getItem() and setItem() methods, you can just use square brackets. For example this piece of code

      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 key that doesn't exist will return nothing.

      Finally, there is a property to get the total number of values ​​in the storage area and to iterate over all 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 .

      Tracking the HTML5 storage area

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

      The storage event is supported wherever the localStorage object is running, 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 it supports browser (if you have done this before with other events, you can skip this section to the end). Trapping the storage event works the same way as trapping 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 a 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 change. For maximum compatibility, you should check if the url property exists, and if not, check the uri property instead.

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

      Limitations in current browsers

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

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

      "QUOTA_EXCEEDED_ERR" is the exception you get if you exceed your 5MB quota. "No" is the answer to the next obvious question: "Can I ask the user for more storage space?". At the time of writing, browsers do not implement any mechanism for web developers to request more storage space. Some browsers (such as Opera) allow the user to control per-site storage quotas, but this is purely user-initiative and not related to what 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 go back to the one we built in the drawing chapter. There is a small problem with this game: if you close the browser window in the middle of the game, you will lose the results. But with HTML5 storage, we can save the game in place, in the browser itself. Open the demo, make a few moves, close the browser tab, and then reopen it. If your browser supports HTML5 storage, the demo page will magically remember your 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). Then all chips are sorted (gPieces , JavaScript array) and store a row and column for each. After that, some additional game states are saved, including the currently selected piece (gSelectedPieceIndex , an 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 the HTML5 store to check the state of the game in the local store. 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 the caveat I mentioned earlier in this chapter and will repeat here: the data is stored as strings. If you're storing something other than strings, you'll need to convert them when you get them. For example, the game in progress flag (gGameInProgress ) is a boolean. In the saveGameState() function, we just store it and don't worry about the data type.

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

      But in the resumeGame() function, we must consider 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 the built-in JavaScript function parseInt() .

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

      Beyond Key/Value Pair: Competitive Vision

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

      One vision is an acronym you already know - SQL. In 2007, Google launched Gears, an open source cross-browser plug-in. source code, which includes an embedded SQLite-based database. This early prototype later influenced the creation of the Web SQL Database specification. Web SQL Database (formerly known as "WebDB") provides a thin wrapper around SQL Database that 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 actions are on the line with the ExecuteSQL method. This string can support any SQL command, including SELECT, UPDATE, INSERT, and DELETE. It's like server-side database programming, except you do it with JavaScript! O joy!

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

      Web SQL database support
      IE Firefox safari Chrome Opera iPhone Android
      4.0+ 4.0+ 10.5+ 3.0+ 2.0+

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

      This all brings us to the next caveat, currently placed 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 several independent implementations to move along the standardization path. While other developers are interested in implementing this specification, the description of the SQL dialect has been left as a mere reference to Sqlite, which is not accepted by the standard.

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

      The Indexed Database API provides what is called an object store, with many ideas borrowed from SQL databases. There are "databases" with "records", each record has a certain number of "fields". Each field has a specific data type, which is defined when the database is created. You can select part of the entries, 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 guide on how IndexedDB works and how IndexedDB compares to Web SQL.

      At the time of writing, IndexedDB has only been implemented in Firefox 4 beta. In 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 has said that IndexedDB is "a great solution for the web."

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

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

      Sent an article with a story about HTML5 LocalStorage in browsers. Let's give him the floor.

      I tried to write the simplest and most understandable guide to using the localStorage technology. The article turned out to be quite small, due to the fact that both the technology itself and the means of working with it do not carry anything complicated. You only need to know a little bit of JavaScript to get started. So, give this article 10 minutes and you can safely add the line “I know how to 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. Pretty much the same as a regular js object, only all properties must be enclosed in quotes.

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

      To understand what localStorage is, just imagine that somewhere in your browser there is such an object 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.

      If to speak JavaScript, then localStorage is a property of the global object of the browser (window). It can be accessed as window.localStorage or just localStorage.

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

      Let's see him live. For example, in Google Chrome, you need to open DevTools (F12), go to the "Resourses" 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, mydomain-1.com cannot access the localStorage of your mydomain-2.com .

      Why do I need localStorage?

      LocalStorage is needed only for 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, 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 to work 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 certain value from the storage by key.

      localStorage.removeItem("Key")

      Delete the key

      localStorage.clear()

      Clearing all storage

      Now you can open a tab with your browser's localStorage and practice writing and retrieving data from this storage yourself. If anything, 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 //Print it to the console: var localValue = localStorage.getItem("myKey"); console.log(localValue); //"myValue" //delete: localStorage.removeItem("myKey"); //clear all storage localStorage.clear() Same, but with square brackets: localStorage["Key"] = "Value" //set the value of localStorage["Key"] //Get the value delete localStorage["Key"] // Deleting a value

      I also want to note that localStorage works great with nested structures, such as 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 by the key "myKey" var returnObj = JSON.parse(localStorage.getItem("myKey")) //parse it back into an object

      You should also be aware that browsers allocate 5MB to localStorage. And if you exceed it, you will get a QUOTA_EXCEEDED_ERR exception. By the way, with its help you can 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 for themselves that this technology already with might and main can be used in your projects. It has good standardization and excellent support, which only develops over time.