Check if cookie exists with JavaScript

0

I have a cookie set with javascript, I created it like this:

document.cookie='gravado=sim'

I do not know how to check if it exists. I need to do a check because if it does not exist, I'll redirect to another page, I also need to know how I can destroy this cookie.

    
asked by anonymous 19.07.2018 / 09:45

1 answer

1

You can check this way

if (document.cookie.indexOf("gravado") < 0) {
        alert("O cookie não existe vou criar");
        document.cookie="gravado=sim";
    }
    else {    
        alert("Já está gravado, vou eliminar");  
        document.cookie ="gravado=; expires=Thu, 01 Jan 1970 00:00:01 GMT;";
    }
    
19.07.2018 / 09:55