This article will demonstrate the method to check whether a cookie exists using JavaScript.
How to Check/Verify if a Cookie Exists in JavaScript?
To check if the cookie exists in the browser or not, use the “checkCookie()” function. In the defined function, check whether the cookie is null using the “document.cookie” attribute. If it is null, it means the cookie does not exist; else cookie exists in the browser.
Example
Create two buttons in an HTML file that will use to set and check the cookie on the browser on the button click:
<input type="button" class="button" value="CheckCookie" onclick="checkCookie()">
Set the cookie using the “document.cookie” attribute with the “prompt()” method to get the input from the user:
var cookie = prompt("Please enter your name");
document.cookie = cookie;
alert("Cookie is created");
}
Now, define a function called “checkCookie()”. Check the condition such that if the value of “document.cookie” is not equal to the null (“”), the cookie exists. Otherwise, it doesn’t exist. Then, call the “setCookie()” to set the cookie on the browser:
if (document.cookie != "") {
alert("Cookie exist ");
alert("Cookie is " + document.cookie);
}
else {
alert("Cookie not exist");
setCookie();
}
}
Output
The output indicates that firstly no cookie exists in the browser. Then, we clicked on the “setCookie” function to set the cookie and fetched its value.
Conclusion
To check if the cookie exists in the browser, use the “checkCookie()” function with the “document.cookie” attribute. In the function checkCookie(), first, check whether the cookie is null. If null, it means the cookie does not exist; else cookie exists in the browser. This article demonstrated the method to check whether a cookie exists or not.