The basic concept

Cookie

A Cookie is a Cookie. As the name suggests, cookies are indeed very small, with a size limit of around 4KB, and were invented in March 1993 by Lou Montulli, a former Netscape employee. Its main uses include storing login information, such as “remember password” when you log in to a website marketplace. This is usually done by storing a piece of data in a Cookie that identifies the user.

localStorage

LocalStorage is a new addition to the HTML5 standard, and it’s nothing new. Back in IE 6, there was something called userData for local storage, and the more common solution was to use Flash for browser compatibility. Today, localStorage is supported by most browsers, so if your site needs to support IE6+, using userData as your polyfill solution is a good choice.

features Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
localStorage 4 3.5 8 10.50 4
sessionStorage 5 2 8 10.50 4

sessionStorage

The sessionStorage interface is similar to that of localStorage, but the life cycle of storing data is different from that of localStorage. Those of you who do back-end development know the word Session, which literally translates to “Session.” SessionStorage is a front-end concept, it can only save part of the data in the current session, refresh the page data still exist. But when the page is closed, the data in sessionStorage will be cleared.

Application scenarios

With an intuitive understanding of these differences, we can discuss the application scenarios of all three.

Given that every HTTP request carries Cookie information, cookies are of course as simple as they can be. A common application scenario is to determine whether a user is logged in. For the user who has logged in, the server will insert an encrypted unique identification code to the Cookie when he logs in. The next time you can read this value to determine whether the current user is logged in. Also used to use cookies to save users in the e-commerce site shopping cart information, now with localStorage, it seems that in this respect can also give cookies a false ~

LocalStorage, on the other hand, takes over Cookie’s job of managing the shopping cart, as well as other tasks. For example, HTML5 games usually generate some local data, and localStorage is also very suitable. If you come across a form with a lot of content, to optimize the user experience, you might want to split the form page into several sub-pages and guide the user through the steps. This is where sessionStorage comes into play.

Safety considerations

It is important to note that not all data is suitable for Cookie, localStorage, and sessionStorage. When using them, you need to be aware of any code that is at risk of XSS injection. As soon as you open the console, you can change their values at will, which means they can do whatever they want with your localStorage if your site has XSS at risk. So never use them to store sensitive data on your system.