0
0
0348raven2015-11-06 10:05:48
HTML
0348raven, 2015-11-06 10:05:48

How to use localstorage and cookies?

What is better and how to use?
For example, there is a script that works for a special version, now it adds styles to each tag in the DOM. In order for them to be saved when navigating through the pages, it is necessary to remember them in cookies or localstorage, as far as I understand. Chose the latter.

function supports_html5_storage() {
    try {
        return 'localStorage' in window && window['localStorage'] !== null;
    } catch (e) {
        return false;
    }
}

var foo = localStorage.getItem("special-version-js");
// ...
localStorage.setItem("special-version-js", foo);

Can someone explain to me in an accessible way what is better to choose and how to use?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivanq, 2015-11-06
@Ivanq

Better localStorage for such purposes.
1. Cookies are stored either temporarily or until the end of the session. localStorage is saved forever.
2. If cookies are disabled by everyone and sundry, localStorage is usually not touched at all.
3. Cookies are difficult to pull out with a script, to parse something there. For localStorage there is getItem.
4. It is generally impossible to delete a cookie (not to assign "", namely to delete it). For localStorage it will be localStorage.removeItem.
5. Cookie assignment looks terrible:

document.cookie = 'mynewcookie=1'; // Нет, это не удаление всех кук и создание одной единственной

Outcome: We use localStorage!
Here I picked up a few pictures:
But there is also localForage, indexedDB, sessionStorage...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question