This blog will describe the method to get the cookie with JavaScript.
How to Get Cookie With JavaScript?
To get the cookie with JavaScript, use the “document.cookie” method in the defined “getCookie()” function. The document.cookie attribute is used to create, read and delete cookies.
Example
In an HTML file, create buttons to set and get the cookies on the browser:
<input type="button" class="button" value="GetCookie" onclick="getCookie()">
Set a cookie by defining the “setCookie()” function that is called when the “SetCookie” button is clicked. On the button click, a prompt message will show that gets the input from the user to set a cookie:
var cookie = prompt("Please enter your name");
document.cookie = cookie;
alert("Cookie is created");
}
Define a “getCookie()” method that will check whether the cookie’s length is not equal to zero. If the condition is evaluated as true, then show an alert message that will show the current saved cookie; else, it tells the cookie is not set and calls the “setCookie()” function to set the cookie:
if (document.cookie.length != 0) {
alert(document.cookie);
}
else {
alert("Cookie is not set");
setCookie();
}
}
As you can see that the user-defined cookie has been successfully fetched:
We have provided all the necessary information relevant to getting the cookie with JavaScript.
Conclusion
To get the cookie with JavaScript, use the “document.cookie” method in the defined “getCookie()” function. The document.cookie attribute is used to create, read and delete cookies. This blog described the method to get the cookie with JavaScript.