How to create a cookie in Javascript?

Asked

Viewed 4,020 times

2

I want to make the next step:

se (cookie[titulo] existe){
    altera o valor dele para $valor
}se nao {
    cria um com $valor
}

NOTE: I have a function that creates the cookie, called GerarCookie(nome,valor,tempo).

Now, how to do this in javascript?

2 answers

3

The code has the function of setting, reading and checking the cookie, very simple.

I hope it gives you a way:

<!DOCTYPE html>
<html>
<head>
<script>

function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function checkCookie() {
    var user=getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
       user = prompt("Please enter your name:","");
       if (user != "" && user != null) {
           setCookie("username", user, 30);
       }
    }
}

</script>
</head>
<body onload="checkCookie()">
</body>
</html>

-3

window.onload = function(){
    checkCookie();
}
 
function checkCookie(){
    var usuario = getCookie("usuario");
    if (usuario != ""){
        alert("Bem vindo " + usuario + "!");
    }else{
        usuario = prompt("Por favor, digite seu nome: ");
        if ((usuario != "") && (usuario != null)){
            setCookie("usuario", usuario, 365);
        }
    }
}
 
function setCookie(chave,valor,validadeDias){
    var validade = new Date();
    validade.setTime(validade.getTime() + validadeDias*24*60*60*1000);
    var validadeUTC = "expires=" + validade.toUTCString();
    document.cookie = chave + "=" + valor + ";" + validadeUTC + ";path=/";
}
 
function getCookie(chave){
    var chaveIgual = chave + "=";
    var pares = document.cookie.split(";");
    for (let i = 0; i < pares.length; i++){
        var par = pares[i];
        while(par.charAt(0) == " "){
            par = par.substring(1);
        }
        if (par.indexOf(chaveIgual) == 0){
            return par.substring(chaveIgual.length);
        }
    }
    return "";
}

Browser other questions tagged

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