Using localStorage for JavaScript needs. How to use local storage for JavaScript Data security localStorage and sessionStorage

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

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

Cookies

Cookies are the 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 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 also be used to easily store data on the client side. Therefore, they are also often used to store general data such as user preferences.

Basic CRUD cookie operations

// 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 may set cookies to expire automatically 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 introduction of the Web Storage API (local and session storage).

Browser support

Cookies have basic support across all major browsers.

Local storage

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

While we can technically only store strings in local storage, this is bypassed by converting to JSON. Thus, 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 storage interface.
  • More secure for storing data on the client.
  • Allows to store more data (all 3 points - in comparison with cookies).

Disadvantages of local storage

  • Allows storing only strings

Browser support

Session storage

Session storage is the second flavor of the 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 leaves the page and closes the browser, the data is cleared.

Basic CRUD Session Storage Operations

// 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 pros, cons, and browser support are exactly the same as local storage.

IndexedDB

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

WebSQL

WebSQL is a client-side relational 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.

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 impressive) 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. Naturally, the standard should have included 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 the latest version of the web application, which is the same for all other users. 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 field of visibility. 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 store is set by the browser, websites can use it to store persistent data that doesn't need to be sent to the server. Data is available by JavaScript and Flash. This can be very handy for Flash games.

GlobalStorage [""]. Foo = "bar"; // foo will be available on any globalStorage website ["ru"]. foo1 = "bar1"; // foo1 will be available on sites "..foo2 =" 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, there is nothing better than databases. 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 full-fledged SQL database. And the work with it is carried out in SQL.

The cookies that we analyzed in the previous lesson are very limited: one cookie can have only 4096 characters, and the number of cookies per domain can be about 30-50, depending on the browser. Therefore, alas, it will not be possible to store a lot of information there. It just so happened historically.

To get around this limitation, an alternative to cookies has appeared in browsers - it is called local storage. In local storage, we can store 5-10 megabytes of information or even more for a long time.

Working with local storage

The localStorage object built into the browser is intended for working with local storage. It has 4 easy-to-understand methods. Here they are:

// Store the value: localStorage.setItem ("Key", "Value"); // Get the value: var value = localStorage.getItem ("Key"); // Removing the value: localStorage.removeItem ("Key"); // Clear all storage: localStorage.clear ();

WITH localStorage you can also work like a regular array:

// Store the value: localStorage ["Key"] = "Value"; // Get the value: var value = localStorage ["Key"]; // Delete value: delete localStorage ["Key"];

Besides the object localStorage there is also an object sessionStorage... Working with it is carried out in the same way, the only difference is that all data from it is automatically destroyed after closing the browser or the tab with the site. Well, localStorage stores data for a long time until this data is removed by a script, or the browser user clears the local storage using the settings.

Examples of

In the following example, we will write the username to local storage:

LocalStorage.setItem ("name", "Ivan");

After a while, we will get this name back:

Alert (localStorage.getItem ("name"));

As you can see, there is nothing complicated here, everything is much simpler than the same work with cookies.

Saving objects

Local storage is not capable of storing JavaScript objects and arrays, although this is often convenient. But there is a way - you need to serialize this data into JSON format - you get a string that can already be stored in localStorage. Then, when we need to get this object back - convert the string from JSON back to an object - and use it calmly.

Let's take a look at this process with an example. Serialize the object and save it to local storage:

// Given an object: var obj = (name: "Ivan", arr :); // Serialize it to "(" name ":" Ivan "," arr ":)": var json = JSON.stringify (obj); // Write to localStorage with the obj key: localStorage.setItem ("obj", json);

After a while, we get the object back:

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

Additional features

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

Determining the name of the key by its number: alert (localStorage.key (number)).

When performing operations with the storage, the event is triggered onstorage... If you bind a function to this event, then the Event object with the following properties will be available in it:

function func (event) (var key = event.key; // key of the data being changed var oldValue = event.oldValue; // old value var newValue = event.newValue; // new value var storageArea = event.storageArea; // storageArea )

Add. material

Storing the array in local storage: https://youtu.be/sYUILPMnrIo

What to do next:

Start solving problems at the following link: tasks for the lesson.

When you have decided everything, move on to studying a new topic.

Some videos may be running ahead as we haven't gone through all of ES6 to this point in the tutorial. Just skip these videos, watch them later.

Submitted an article explaining HTML5 LocalStorage in browsers. We 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 the technology itself and the means of working with it do not carry anything complicated. You just need to know a little JavaScript to get started. So, take this article 10 minutes and you can safely add the line "I can work with localStorage" to your resume.

What is localStorage?

This is how a JavaScript object looks like:

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

This is how JSON looks like. Much like a regular js object, only all properties must be enclosed in quotes.

("firstName": "Ivan", "lastName": "Ivanov", "address": ("streetAddress": "Moskovskoe highway, 101, apt. 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 close the browser completely.

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

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

Let's see it live. For example, in Google chrome you need to open DevTools (F12), go to the "Resources" tab and in the left pane you will see localStorage for this domain and all the values ​​it contains.

By the way, you should know how localStorage works with domains. For each domain, your browser creates its own localStorage object and can only be edited or viewed on that domain. For example, the domain 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 for working with it.

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

A method that adds a new key with a value to localStorage (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")

Removing the key

localStorage.clear ()

We clear all storage

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

// Add or change the value: localStorage.setItem ("myKey", "myValue"); // now you have the "myKey" key with the value "myValue" stored in localStorage // Print it to the console: var localValue = localStorage.getItem ("myKey"); console.log (localValue); // "myValue" // remove: localStorage.removeItem ("myKey"); // clear all storage localStorage.clear () The same, but with square brackets: localStorage ["Key"] = "Value" // set the value to localStorage ["Key"] // Get 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 "myKey" key var returnObj = JSON.parse (localStorage.getItem ("myKey")) // parse it back an object

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

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

Familiarity with the basics of JavaScript programming often starts with creating the simplest applications, such as the electronic notebook, which we use to record things and events that we can forget about. But such applications have one problem - after reloading the page, the list of all previously left records disappears, that is, the application returns to its original state.

There is a very simple way out of this situation by using the localStorage mechanism. Due to the fact that localStorage allows us to store the necessary data on the user's computer, the above list of scheduled tasks and events will still be available after reloading the page, in addition, localStorage is a surprisingly very simple way of storing data and accessing it when needed.

What is localStorage?

It is a local storage engine that is part of the Web Storage technology as defined by the HTML5 specification. There are two storage options allowed by this specification:

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

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

Html

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

  • A field for entering new records (events, cases, etc.).
  • Button to confirm the entered entry.
  • Button for clearing an already created to-do list.
  • An unordered list that will be populated with new entries.
  • Finally, we need a div as a container to contain messages to be displayed to the user, such as a warning that he forgot to enter a value for the next record, leaving the input field blank.

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








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

JavaScript

Regarding the structure of the simplest notepad application in our example, the first thing we need to do is ensure that the button click event is tracked. "Add a note" and check if any information is entered into the text field for recording, that is, at the moment of pressing the button, it should not be empty. Something like this:

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

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

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

// Add an entry to the 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 jQuery code is used. At the point of accessing the localStorage object, we must specify the data we are saving in the form of a key / value. An arbitrary name can be used for the key, and I named it "todos", then we need to indicate what we, in fact, need to keep in memory. In this case, it is a complete piece of HTML markup that is included in an unordered list (located between tags) that displays all previously entered records by the user. From the code, you can see that we simply retrieve the fragment we need using the jQuery .html () method and at the end, after completing all the necessary actions, we set the return value of the function 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 the further normal operation of the application, we need to check if localStorage contains the information previously saved on the computer and, if so, display it for the user. Since the name of our key is "todos", we must check for its existence as follows:

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

    }

    To check for the presence of data, we used the usual if statement and, when the specified condition was met, we simply retrieved all the data from the local storage, placing it as HTML markup inside an unordered list, with the help of which the records entered earlier by the user are displayed.

    If you test your simplest application, you will find that after reloading the page, everything stays in place. And now, the last thing that remains for us to do is create a function with which the user, if necessary, could delete all his records. This is accomplished 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.):

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

    The result is a fully functional application. And putting all the above snippets together, we get the complete application code:

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

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

    * Translator's note.

    Post Views: 475