JavaScript

Get Cookie With JavaScript

On a user’s computer, Cookies save useful information related to the user in the form of data chunks. The website sends cookies to the browser when a user visits or navigates to it. The browser will then save it and send the cookie to the server. This operation permits the website to remember the visitor’s preferences or login information and offer a personalized experience.

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="SetCookie" onclick="setCookie()">

<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:

function setCookie() {

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:

functiongetCookie() {
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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.