HTML5 client-side local data storage. Local storage Local storage

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 COOKIE, but 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 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.

Delete data

LocalStorage ("key"); // delete the data under the passed key
localStorage.clear (); // clear 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 cookies that we examined 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 \u003d localStorage.getItem ("Key"); // Removing the value: localStorage.removeItem ("Key"); // Clear all storage: localStorage.clear ();

FROM localStorage you can also work like a regular array:

// Store the value: localStorage ["Key"] \u003d "Value"; // Get the value: var value \u003d 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 difficult 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 saved 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. Let's serialize the object and save it to local storage:

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

After a while, we get the object back:

// Get data back from localStorage as JSON: var json \u003d localStorage.getItem ("obj"); // Convert them back to JavaScript object: var obj \u003d 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 \u003d event.key; // key of the data being changed var oldValue \u003d event.oldValue; // old value var newValue \u003d event.newValue; // new value var storageArea \u003d 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 have not gone through all ES6 to this point in the tutorial. Just skip these videos, watch later.

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, volume is very important for the mobile Internet. 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. A cookie is a key-value pair that is stored locally in a 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 storage is 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 for 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, data is retained even after closing the tab / window / browser.

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, databases have not yet come up with anything better. 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.

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 \u003d (wheels: 4, doors: 4, engine: 1, name: "Jaguar")

And 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 you have an object embedded that we can use. At the same time, this object does not clear the values \u200b\u200bthat we write there if we reload the page or even completely close the browser.

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 "Resourses" tab and in the left pane you will see localStorage for this domain and all the values \u200b\u200bit contains.

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

We clear all storage

Now you can open the localStorage tab of your browser 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 \u003d localStorage.getItem ("myKey"); console.log (localValue); // "myValue" // remove: localStorage.removeItem ("myKey"); // clear all storage localStorage.clear () The same, only with square brackets: localStorage ["Key"] \u003d "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 \u003d (item1: 1, item2:, item3: "hello"); var serialObj \u003d JSON.stringify (obj); // serialize it localStorage.setItem ("myKey", serialObj); // write it to the storage using the "myKey" key var returnObj \u003d 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 \u003d\u003d 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.

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.