Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 31, 2023 01:54 am

Read and Create Cookies in JavaScript


Even if you haven't used cookies before, you are probably already familiar with them. Almost every website that you visit asks to accept cookies.


So, what are cookies? Cookies are basically small pieces of text that contain some information relevant to you or the website you are visiting. This information is stored inside your browser and allows websites to give you a personalized experience, access to protected sections of the website or gather analytics data.


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



The Document interface contains a property called cookie that you use to read and write cookies. Simply using document.cookie will give you back a string that contains all your cookies separated by a semi-colon. The following example shows all the cookies that are set on my browser for the Wikipedia homepage.



























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 the reopened it later. After a couple of refreshes and some waiting time, the value stored in the cookies had 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 long I spent on a page etc.


The value returned by document.cookie shows that we only get back the name and value of 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 our read_cookie() function to get the values from all of them. The value of the GeoIP cookie shows the location to be New York because it is masked by my VPN. You can try using the above function on Wikipedia or any other website yourself 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 also create a new cookie by using the 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 that you have set for the cookie. These are the only required values for creating a cookie but you can also pass down 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 execute the following code:





1
document.cookie = "site_theme=christmas";

Setting Expiration Time


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





1
;expires:GMT-string-fromat-date

Our site_theme cookie above is set to expire as soon as your close the browser. You can verify this by closing the browser and then trying to read the cookie using the read_cookie() function we wrote above. We can extend its life by 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 28 Dec 2023. Try closing the browser window and reopen the page again to see that the cookie is still available for you to read.


Another way to set cookie expiration time is by using the following string:





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

Let's say you want the cookie to expire a week after it has been 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 point of 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 you cannot set cookies for any 3rd party domain that you want. For example, a script running on 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 domain and path values. You can set these two values by using the following string:





1
;domain=domain;path=path

The domain is set to the host of current location by default. Since we created our earlier cookies by opening the browser console on https://code.tutsplus.com/tutorials, our cookie is also accessible only 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 that is accessible on all subdomains of tutsplus.com by executing 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 to be available only on the URLs that contain /tutorials in their path, you can do so 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 above line, the cookie won't be accessible on the URL https://code.tutsplus.com/categories/javascript because of the path restriction.


Modifying and Deleting Cookies in JavaScript


When we were reading cookie information from Wikipedia at the beginning of this tutorial, you might have noticed that the value of the cookie enwikiwmE-sessionTickTickCount was updating with the passage of time. There are a variety of reasons why you might want to update the value of a cookie periodically 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 modify existing cookies. Continuing our example from the previous section, let's say you want to change the value of site_theme cookie to new_year and change the expiration date to the new year as well. You can do so 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";

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


Setting the value of max-age to 0 will make the cookie expire in next 0 seconds or in other words now. Similarly, you can also set the value of expires to some date in the past and it will clear 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 the lines above will work if you want to delete a cookie.


One important thing to remember when you are modifying or deleting cookies is that the domain and path values have to match the cookie that you are modifying or deleting.


Final Thoughts


In this tutorial, we learned how to manage cookies in JavaScript. You should now be able to read data from cookies, create new cookies, and modify or delete existing cookies. While cookies are great for storing information, there are a few things to be kept in mind. First, cookie storage is limited to about 4KB so you shouldn't be using them to store a large amount of information. Second, you also cannot create a large number of cookies for same domain. The limit varies across browsers and is fairly generous at around 300 at least. This should generally be sufficient.


If you are looking to store a large amount of data and want to only access it locally, you might consider using either Local Storage or Session Storage.




Original Link: https://code.tutsplus.com/tutorials/managing-cookies-in-javascript--cms-93787

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code