Read and create cookies in JavaScript


Even if you’ve never used cookies before, you’re probably already familiar with them. Almost all websites you visit require you to accept cookies.

So what are cookies? Cookies are basically small pieces of text that contain some information that is relevant to you or the website you are visiting. This information is stored within your browser and allows websites to offer you a personalized experience, access secure sections of the website or collect analytical data.

In this tutorial, I’ll show you how to manage cookies with JavaScript.

The Document interface contains a property called cookie you use to read and write cookies. Just using document.cookie will return you a string containing all of your cookies separated by a semicolon. The example below shows all the cookies set on my browser for the Wikipedia home page.

1
let all_cookies = document.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 page and reopened it later. After a couple of updates and some waiting time, the value stored in the cookies changed to the following:

1
let all_cookies = document.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 can see, the values ​​in cookies can change over time. Websites can use them to track things like how much time I spent on a page, etc.

The value returned by document.cookie shows that we only retrieve the name and value of the cookies stored in the browser. Let’s write a JavaScript function that will give us the value of a stored cookie once we pass its name.

1
function read_cookie(name) {
2
  let all_cookies = document.cookie.split("; ");
3
  let cookie_name = name + "=";
4
5
  for (let i = 0; i < all_cookies.length; i++) {
6
    let clean_cookie = all_cookies[i];
7
    if (clean_cookie.startsWith(cookie_name)) {
8
      return clean_cookie.substring(cookie_name.length, clean_cookie.length);
9
    }
10
  }
11
} 

There are currently four cookies on Wikipedia that I can access using JavaScript. I used ours read_cookie() function to get the values ​​from all of them. The GeoIP cookie value shows that the location is New York because it is masked by my VPN. You can try using the above function yourself on Wikipedia or any other website to retrieve the 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 also create a new cookie using the file cookie property and setting its value to a string that has the form key=value. The key here is the name of the cookie and value is the value you set for the cookie. These are the only values ​​required for the creation of a cookie but you can also pass other important information.

To see how setting a cookie value works, you can visit https://code.tutsplus.com/tutorials and then open the browser console to run the following code:

1
document.cookie = "site_theme=christmas";

Expiration time setting

Unless otherwise specified, the cookies set are designed to expire at the end of a browsing session when users close their browser. If you would like your cookie to expire at a specific time in the future, you should set an expiration date by adding the following string to your cookie.

1
;expires:GMT-string-fromat-date

Our site_theme the above cookie is set to expire as soon as you close your browser. You can check this by closing your browser and then trying to read the cookie using the read_cookie() function we wrote above. We can extend its life using the following code snippet:

1
 document.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 December 28, 2023. Try closing your browser window and reopening the page again to verify that the cookie is still available for reading.

Another way to set cookie expiration is to use the following string:

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

Let’s say you want the cookie to expire a week after it’s set. You can determine the number of seconds by calculating 60*60*24*7. The following line will set the cookie for you:

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

You can set the expires value when you want the cookie to expire at a specific time and the max-age value when you want the cookie to expire after a specific period.

Setting the domain and path

It is important to remember that it is not possible to set cookies for any desired third-party domain. For example, a script running on www.tutsplus.com cannot set a cookie for wikipedia.org. This is done as a security measure.

You can have even more control over the accessibility of a cookie by setting its own domain And path values. You can set these two values ​​using the following string:

1
;domain=domain;path=path

The domain is set to the host of the current location by default. Since we created our previous cookies by opening the browser console on https://code.tutsplus.com/tutorialsour cookie is also only accessible on the code.tutsplus.com subdomain. Try using the read_cookie() function on the browser console for https://design.tutsplus.com/tutorials and it will be undefined.

You can create a cookie accessible on all subdomains of www.tutsplus.com by running the following line:

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

Similarly, you can also provide a path for which the cookie will be accessible. Let’s say you want the site_theme cookie is only available on the URLs they contain /tutorials in their path, you can do this with the following line:

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

After executing the previous line, the cookie will not be accessible on the URL https://code.tutsplus.com/categories/javascript due to route limitation.

Editing and deleting cookies in JavaScript

When we were reading about cookies from Wikipedia at the beginning of this tutorial, you may have noticed that the value of the cookie enwikiwmE-sessionTickTickCount it was updating as time went on. There are several reasons why you may want to periodically update the value of a cookie, such as counting the number of visits or updating user preferences.

Once you know the basics of creating cookies, you will also be able to easily edit existing cookies. Continuing our example from the previous section, let’s say you want to change the value of site_theme biscuit a New Year’s and also change the due date to the new year. You can do this with the following code:

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

Remember when I said we can specify when a cookie expires by passing the file expires or max-age values? We can also use them to delete a cookie.

Setting the value of max-age a 0 will cause the cookie to expire in the next 0 seconds or in other words now. Similarly, you can also set the value of expires to a date in the past and will delete the cookie.

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

Both of the above lines will work if you want to delete a cookie.

An important thing to remember when editing or deleting cookies is that the domain And path the values ​​must match the cookie you are editing or deleting.

Final thoughts

In this tutorial, we learned how to handle cookies in JavaScript. You should now be able to read data from cookies, create new cookies, and edit or delete existing cookies. While cookies are great for storing information, there are a few things to keep in mind. First, cookie storage is limited to around 4KB, so you shouldn’t use them to store a large amount of information. Secondly, it is also not possible to create a large number of cookies for the same domain. The limit varies between browsers and is quite generous, at least around 300. This should generally be sufficient.

If you are looking to store a large amount of data and only want to access it locally, you may want to consider using local storage or session storage.



Source link

By LocalBizWebsiteDesign

Leave a Reply

Your email address will not be published. Required fields are marked *