How to create a function in javascript to check if a cookie has been saved or not?

0

I am a student of information systems and I am learning how to create cookies in javascrit using functions and webstorege, but I am having problems when creating the function to check if a cookie has been saved or not.

See the code:

<!DOCTYPE html>
<html>
    <head>
        <script>
            function setCookie(cname,cvalue,exdays){
                var d = new Date();
                d.setTime(d.getTime()+(exdays*60*60*24*365));
                var expires = "expires=" + d.toUTCString();
                document.cookie = cname + "=" + cvalue + ";" + expires +";paths=/";
                alert("cookie inserido com sucesso");

            }

        function getCookie(cname, cvalue, exdays){
            var d = new Date();
            d.getTime(d.getTime()+(exdays*60*60*24*365));
            var expires = "expires" + d.toUTCString();
            document.cookie = cname +"=" + cvalue + ";" + expires + ";paths=/";
            alert("Cookie exibido");

        }

    function checCookie(cname, cvalue, exdays){
            var d = new Date();
            d.getTime(d.getTime()+(exdays*60*60*24*365));
            var expires = "expires" + d.toUTCString();
            document.cookie = cname +"=" + cvalue + ";" + expires + ";paths=/";
            alert("Cookie exibido");

        }

    function apagarCookie(cname, cvalue, exdays){
            var d = new Date();
            d.getTime(d.getTime()+(exdays*60*60*24*365));
            var expires = "expires" + d.toUTCString();
            document.cookie = cname +"=" + cvalue + ";" + expires + ";paths=/";
            alert("Cookie exibido");

        }


        </script>
    </head>
    <body>
        <center>
            <h1>Testes de Cookies</h1>
            <button id="btncookie" onclick="setCookie()">Gravar Cookies</button>
            <button id="btnExibir" onclick="getCookie()">Exibir Cookie</button>

        </center>
    </body> 
</html>

What is wrong with the checkCookie function?

How can I fix this error?

    
asked by anonymous 24.03.2018 / 16:06

2 answers

0

The code of the checkCookie function you put here is actually saving a new cookie. To read it you need to access the document.cookie object, browse the string until you find the index you want. It would look something like this:

function checkCookie(cname){
    var cookie = document.cookie.split(';');  
    var index= -1;

    cookie.forEach(function(c, i){

        var strIndex = c.split("=")[0]; 
        if (strIndex && strIndex.length > 0 && strIndex.trim() === cname)
            index = i;  
    });

    return index>-1;
}
    
24.03.2018 / 17:36
0

Both their getCookie() and checkCookie() functions are saving cookies instead of retrieving them (if they exist).

You are also passing "values" to these functions that you do not really need, the only relevant information is the name of a cookie, you do not have to pass the expiration date because if the cookie has expired, it will not be available for query.

Using replace() and RegExp() on document.cookie you can retrieve the values of a given cookie by its name (if it exists) or, encapsulating this logic in a function can alternatively return false if there is no exists).

The following example expresses this condition:

let getCookie(name) {
    return document.cookie.replace(new RegExp("(?:(?:^|.*;)\s*" + name.replace(/[\-\.\+\*]/g, "\$&") + "\s*\=\s*([^;]*).*$)|^.*$"), "$1") || false
}

You can use both to check if a cookie exists and to return (get) its value because it will return the value {String} or {Boolean} false if it does not exist:

// verificar dentro de condição 'if'
if ( getCookie('nome_do_cookie') ) {
    // verdadeiro, cookie existe
}
// ou por atribuição
let cookieTarget = getCookie('nome_do_cookie')
if ( cookieTarget ) {
    // ...
}
// ou mesmo definir uma ação baseada na condição
function funcao001() {}
function funcao002() {}
let customHandler = (cookieTarget) ? funcao001 : funcao002
// usar
customHandler() {
    // fazer algo...
}
// caso o cookie exista a função retornará seu valor:
let customObject = {
    qualquercoisa: 'valor',
    cookie: getCookie('nome_do_cookie') // valor ({String}) ou "booleano" 'false'
}
    
24.03.2018 / 20:10