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

Asked

Viewed 222 times

0

I’m an information systems student and I’m learning how to create cookies in javascrit using functions and webstorege, but I’m having trouble creating the function to check if a cookie has been recorded or not.

Look at 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’s wrong with the checkCookie function?

How can I correct this mistake?

  • I believe Cookie is only verifiable after page reload, but I may be wrong.

  • I don’t know if you’d be willing to change, but try using localStorage in Javascript as it’s safer and easier to use.

2 answers

0

The code of the checkCookie function you placed here is actually saving a new cookie. To read it you need to access the Document.cookie object, navigate the string until you find the desired index. 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;
}

0

Both its functions getCookie() as checkCookie() are saving cookies instead of retrieving them (if any).

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

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

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 either to check if a cookie exists or to return (get) its value because it will return the value {String} or {Boolean} false if there is no:

// 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`
}

Browser other questions tagged

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