How to use cookies in javascript

Asked

Viewed 4,711 times

2

I know how to create cookies in Javascript, but I don’t know how to apply them in some project. Someone could post an example of how to use cookies?

  • 1

    Check out the link https://answall.com/questions/217192/javascript-redirecionar-e-setar-cookies helped me a lot.

1 answer

5

How did I respond in Save cookie and read its value when accessing the website to check if expired

You must use document.cookie to create cookies as needed and the script must run on a server (like Apache for example), local access (protocol file://) usually does not work with cookies.

note that some browsers block cookies generated by http://localhost, to get around the problem use the address http://127.0.0.1

To create a cookie we must use the supported parameters are:

  • ;path= must contain the HTTP path/path that can be used to limit where the cookie should be accessible
  • ;expires= must contain date in GMT format of when it will expire
  • ;max-age= should contain the time in seconds from when the cookie should expire, no need to use max-age and expires at the same time
  • ;secure specifies that the cookie should only work on the HTTPS protocol

The cookie name (key) and value can be encoded with encodeURIComponent to prevent characters such as spaces or ; make the dice get lost.

Example of how to create a cookie:

document.cookie="<chave>=<valor>; expires=<data para expirar>; path=<caminho HTTP>";

An example cookie that should expire on 12/31/2018 at 23:59:59 (in GMT):

document.cookie="chave=valor; expires=Mon, 31 Dec 2018 23:59:59 GMT;path=/"

Note that maybe instead of cookies you can use localStorage and sessionStorage (https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage)

For example with sessionStorage:

// Salva dados
sessionStorage.setItem("foo", "bar");

// Pega os dados
alert( "foo = " + sessionStorage.getItem("foo"));

For example with localStorage:

// Salva dados
localStorage.setItem("baz", "bar");

// Pega os dados
alert( "foo = " + localStorage.getItem("baz"));

The difference between sessionStorage and localStorage is that the first expires whenever the browser is closed, the second stays

Note: if you want to use localStorage with time to expire see this other answer I created How to make Local Storage expire?


But like the question about cookies, I will show an example with such, so I created the following functions:

function getCookie(k) {
    var c = String(document.cookie).split(";");
    var neq = k + "=";

    for (var i = 0; i < c.length; i++) {
        var d = c[i];

        while (d.charAt(0) === " ") {
            c[i] = c[i].substring(1, d.length);
        }

        if (c[i].indexOf(neq) === 0) {
            return decodeURIComponent(c[i].substring(neq.length, c[i].length));
        }
    }

    return null;
}

function setCookie(k, v, expira, path) {
    path = path || "/";

    var d = new Date();
    d.setTime(d.getTime() + (expira * 1000));

    document.cookie = encodeURIComponent(k) + "=" + encodeURIComponent(v) + "; expires=" + d.toUTCString() + "; path=" + path;
}

To set your ID cookie, do this:

setCookie("chave", "valor");

To read the cookie we call chave do so:

var resultado = getCookie("chave");
console.log(resultado); //Exibe o resultado ou exibe null se tiver expirado ou não for acessível a partir do PATH da URL atual

To set a time to expire the cookie do so:

setCookie("foo", "baz", 3600);//Expira o cookie "foo" em uma hora

To restrict the cookie only to certain HTTP paths (routes) use so:

setCookie("bar", "baz", false, "/pasta2/");//o cookie só estara acessível em urls como http://site/pasta2/*

If you want to set a time to expire on a specific PATH use so:

setCookie("bar", "baz", 86400, "/pasta3/");//o cookie só estará acessível em urls como http://site/pasta3/* e irá expirar em 24 horas

Browser other questions tagged

You are not signed in. Login or sign up in order to post.