Check if cookie exists with Javascript

Asked

Viewed 1,689 times

0

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

document.cookie='gravado=sim'

I don’t know how I’m gonna make sure he exists. I need to make a check because if it does not exist, I will redirect to another page, also need to know how to destroy this cookie

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;";
    }
  • Thank you, and to destroy the session I do how? in php is very simple, I can use the command Destroy or unset and ready, already in javascript I do not know how to do

  • Please mark the answer as right I will correct the answer

  • ready, I scored

  • I searched and all I found was a way to set the time for the cookie to expire, I wanted something I could do right away, for example, when I click something or after performing a certain task I can delete the cookie

  • You can always assign a value that determines your interest e.g. saved=deleted

Browser other questions tagged

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