How to create a Javascript cookie?

2

I want to do the following 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?

    
asked by anonymous 25.02.2016 / 00:22

2 answers

1

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

I hope you get a path:

<!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>
    
25.02.2016 / 00:26
-3

window.onload = function () {     checkCookie (); }

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

function setCookie (key, value, ValidityDays) {     var validity = new Date ();     validity.setTime (validity.getTime () + validityDays * 24 * 60 * 60 * 1000);     var validityUTC="expires=" + validity.toUTCString ();     document.cookie = key + "=" + value + ";" + validityUTC + "; path = /"; }

function getCookie (key) {     var keyIgual = key + "=";     var pairs = document.cookie.split (";");     for (let i = 0; i

22.11.2018 / 23:49