Sunday, May 5, 2024
HomeWeb developmentLearn and Create Cookies in JavaScript

Learn and Create Cookies in JavaScript


Even when you have not used cookies earlier than, you’re most likely already conversant in them. Virtually each web site that you simply go to asks to simply accept cookies.

So, what are cookies? Cookies are principally small items of textual content that comprise some data related to you or the web site you’re visiting. This data is saved inside your browser and permits web sites to present you a customized expertise, entry to protected sections of the web site or collect analytics information.

On this tutorial, I’ll present you the best way to handle cookies with JavaScript.

The Doc interface comprises a property referred to as cookie that you simply use to learn and write cookies. Merely utilizing doc.cookie will provide you with again a string that comprises all of your cookies separated by a semi-colon. The next instance exhibits all of the cookies which might be set on my browser for the Wikipedia homepage.

1
let all_cookies = doc.cookie;
2
3
console.log(all_cookies);
4
/* Outputs:
5
GeoIP=IN:State_Code:State:My_Latitude:My_Longitude:v4; enwikiwmE-sessionTickLastTickTime=1675054195383; enwikiwmE-sessionTickTickCount=1; enwikimwuser-sessionId=7ed98fe7399e516cff54
6
*/

I closed the web page and the reopened it later. After a few refreshes and a few ready time, the worth saved within the cookies had modified to the next:

1
let all_cookies = doc.cookie;
2
3
console.log(all_cookies);
4
/* Outputs:
5
GeoIP=IN:State_Code:State:My_Latitude:My_Longitude:v4; enwikimwuser-sessionId=7ed98fe7399e516cff54; enwikiwmE-sessionTickLastTickTime=1675058494564; enwikiwmE-sessionTickTickCount=16
6
*/

As you’ll be able to see, the values in cookies can change over time. Web sites can use them to trace issues like how lengthy I spent on a web page and so on.

The worth returned by doc.cookie exhibits that we solely get again the title and worth of cookies saved within the browser. Let’s write a JavaScript perform that can give us the worth of a saved cookie as soon as we go its title.

1
perform read_cookie(title) {
2
  let all_cookies = doc.cookie.cut up("; ");
3
  let cookie_name = title + "=";
4
5
  for (let i = 0; i < all_cookies.size; i++) {
6
    let clean_cookie = all_cookies[i];
7
    if (clean_cookie.startsWith(cookie_name)) {
8
      return clean_cookie.substring(cookie_name.size, clean_cookie.size);
9
    }
10
  }
11
} 

There are at the moment 4 cookies on Wikipedia that I can entry utilizing JavaScript. I used our read_cookie() perform to get the values from all of them. The worth of the GeoIP cookie exhibits the situation to be New York as a result of it’s masked by my VPN. You possibly can strive utilizing the above perform on Wikipedia or some other web site your self to retrieve cookie values:

1
let geo_ip = read_cookie("GeoIP");
2
// Outputs: US:NY:New_York:40.74:-73.99:v4
3
4
let session_id = read_cookie("enwikimwuser-sessionId");
5
// Outputs: 398c37df147f0b377825

Creating Cookies in JavaScript

You can too create a brand new cookie by utilizing the cookie property and setting its worth to a string that has the shape key=worth. The key right here is the title of the cookie and worth is the worth that you’ve got set for the cookie. These are the one required values for making a cookie however you can too go down different necessary data.

To see how setting a cookie worth works, you’ll be able to go to https://code.tutsplus.com/tutorials after which open the browser console to execute the next code:

1
doc.cookie = "site_theme=christmas";

Setting Expiration Time

Until specified in any other case, cookies you set are designed to run out on the finish of a looking session when customers shut the browser. If you need your cookie to run out at a particular time sooner or later, you need to set an expires date by including the next string to your cookie.

1
;expires:GMT-string-fromat-date

Our site_theme cookie above is ready to run out as quickly as your shut the browser. You possibly can confirm this by closing the browser after which making an attempt to learn the cookie utilizing the read_cookie() perform we wrote above. We are able to lengthen its life by utilizing the next code snippet:

1
 doc.cookie = "site_theme=christmas;expires=Thu, 28 Dec 2023 08:58:01 GMT";
2
 // The cookie will now expire on Thu, 28 Dec 2023 08:58:01 GMT

The cookie will now expire on 28 Dec 2023. Strive closing the browser window and reopen the web page once more to see that the cookie continues to be out there so that you can learn.

One other technique to set cookie expiration time is by utilizing the next string:

1
;max-age=cookie-age-in-seconds

For example you need the cookie to run out every week after it has been set. You possibly can decide the variety of seconds by calculating 60*60*24*7. The next line will set the cookie for you:

1
doc.cookie = `site_theme=christmas;max-age=${60*60*24*7}`;
2
// The cookie will now expire one week from now

You possibly can set the expires worth if you need the cookie to run out at a particular level of time and the max-age worth if you need the cookie to run out after a particular interval.

Setting the Area and Path

It is very important keep in mind that you can not set cookies for any third get together area that you really want. For instance, a script working on tutsplus.com can’t set a cookie for wikipedia.org. That is executed as a safety measure.

You possibly can have much more management over the accessibility of a cookie by setting its area and path values. You possibly can set these two values by utilizing the next string:

1
;area=area;path=path

The area is ready to the host of present location by default. Since we created our earlier cookies by opening the browser console on https://code.tutsplus.com/tutorials, our cookie can be accessible solely on the code.tutsplus.com subdomain. Strive utilizing the read_cookie() perform on the browser console for https://design.tutsplus.com/tutorials and will probably be undefined.

You possibly can create a cookie that’s accessible on all subdomains of tutsplus.com by executing the next line:

1
doc.cookie = "site_theme=christmas;expires=Thu, 28 Dec 2023 08:58:01 GMT;area=tutsplus.com";

Equally, you can too present a path for which the cookie can be accessible. For example you need the site_theme cookie to be out there solely on the URLs that comprise /tutorials of their path, you are able to do so with the next line:

1
 doc.cookie = "site_theme=christmas;expires=Thu, 28 Dec 2023 08:58:01 GMT;area=tutsplus.com;path=/tutorials";

After executing the above line, the cookie will not be accessible on the URL https://code.tutsplus.com/classes/javascript due to the trail restriction.

Modifying and Deleting Cookies in JavaScript

Once we have been studying cookie data from Wikipedia firstly of this tutorial, you may need seen that the worth of the cookie enwikiwmE-sessionTickTickCount was updating with the passage of time. There are a selection of explanation why you may need to replace the worth of a cookie periodically equivalent to counting the variety of visits, or updating person preferences.

As soon as you realize the fundamentals of making cookies, additionally, you will have the ability to simply modify current cookies. Persevering with our instance from the earlier part, for example you need to change the worth of site_theme cookie to new_year and alter the expiration date to the brand new yr as properly. You are able to do so with the next code:

1
doc.cookie = "site_theme=new_year;expires=Mon, 1 Jan 2024 08:58:01 GMT;area=tutsplus.com;path=/tutorials";

Do you keep in mind once I mentioned that we will specify when a cookie expires by passing the expires or max-age values? We are able to additionally use them to delete a cookie.

Setting the worth of max-age to 0 will make the cookie expire in subsequent 0 seconds or in different phrases now. Equally, you can too set the worth of expires to some date up to now and it’ll clear the cookie.

1
doc.cookie = "site_theme=new_year;max-age=0;area=tutsplus.com;path=/tutorials";
2
doc.cookie = "site_theme=new_year;expires=Mon, 1 Jan 2001 08:58:01 GMT;area=tutsplus.com;path=/tutorials";

Each the traces above will work if you wish to delete a cookie.

One necessary factor to recollect if you find yourself modifying or deleting cookies is that the area and path values need to match the cookie that you’re modifying or deleting.

Remaining Ideas

On this tutorial, we realized the best way to handle cookies in JavaScript. It’s best to now have the ability to learn information from cookies, create new cookies, and modify or delete current cookies. Whereas cookies are nice for storing data, there are some things to be stored in thoughts. First, cookie storage is restricted to about 4KB so that you should not be utilizing them to retailer a considerable amount of data. Second, you additionally can’t create a lot of cookies for similar area. The restrict varies throughout browsers and is pretty beneficiant at round 300 not less than. This could usually be ample.

If you’re trying to retailer a considerable amount of information and need to solely entry it domestically, you may think about using both Native Storage or Session Storage.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments