I create cookies in JavaScript, but I do not know how to apply them to some project. Could anyone post an example of how to use cookies?
I create cookies in JavaScript, but I do not know how to apply them to some project. Could anyone post an example of how to use cookies?
How do I respond to Save cookie and read its value when accessing web site to check if expired
You should use document.cookie
to create cookies as needed and the script should run on a server (like Apache for example), local access ( file://
protocol) generally does not work with cookies.
Note that some browsers block cookies generated by
http://localhost
, to work around the problem use thehttp://127.0.0.1
To create a cookie we should 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=
should contain date in GMT format when it will expire ;max-age=
must contain the time in seconds when the cookie should expire, it is not necessary to use max-age
and expires
at the same time ;secure
specifies that the cookie should only work over the HTTPS protocol Cookie name and value can be encoded with encodeURIComponent
to prevent characters like spaces or ;
from causing data to be 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 perhaps instead of cookies you can use localStorage
and sessionStorage
( link )
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 one expires whenever the browser is closed, the second stays
Note: If you want to use
localStorage
with time to expire, see this other response that I created How do I get Local Storage out?
But as the question about cookies, I will show an example with such, then 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 (routes) use this way:
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 in a specific PATH use this:
setCookie("bar", "baz", 86400, "/pasta3/");//o cookie só estará acessível em urls como http://site/pasta3/* e irá expirar em 24 horas
Use this pegaCookie()
function that will return the value of the cookie
indicated in nome_do_cookie
(replace with the name you created the cookie
). Assign the function return to a valor_cookie
variable (for example). The value of cookie
will be stored in this variable, so you can use it anywhere you want in your code, checking whether it has any value or not.
function pegaCookie(i){
var n = i + "=";
var k = document.cookie.split(';');
for(var i=0; i<k.length; i++){
var c = k[i];
while(c.charAt(0) == " "){ c = c.substr(1); }
if(c.indexOf(n) == 0){ return c.substr(n.length, c.length); }
}
return "";
}
var valor_cookie = pegaCookie("nome_do_cookie");
If the valor_cookie
variable is empty, cookie
does not exist or has expired. Example:
if(valor_cookie){
alert(valor_cookie);
}else{
alert("Cookie não disponível");
}