Category: Cookies

  • Deleting Cookies

    In order to delete cookies with JavaScript, we can set the expires date to a past date. We can also delete a cookie using the max-age attribute. We can delete the cookies explicitly from the browser.

    Deleting cookies with JavaScript removes small bits of data that websites store on a user’s computer. Cookies are used to track a user’s browsing activity and preferences.

    It is important to note that deleting cookies can have unintended consequences. For example, if you delete a cookie that is used to authenticate you to a website, you will be logged out of the website. You should only delete cookies if you are sure that you want to do so.

    Different Ways to Delete the Cookies

    There are three different ways to delete the cookies −

    • Set the past expiry date to the ‘expires’ attribute.
    • Use the ‘max-age’ attribute.
    • Delete cookies explicitly from the browser.

    Delete Cookies using ‘expires’ Attribute

    When you set the past expiry date as a value of the ‘expires’ attribute, the browser automatically deletes the cookie.

    Syntax

    Follow the syntax below to delete a cookie by setting up the past expiry date as a value of the ‘expires’ attribute.

    document.cookie ="data1=test1;expires=Tue, 22 Aug 2023 12:00:00 UTC;";

    In the above syntax, we have set the past date as a value of the ‘expires’ attribute. You may set any past date.

    Example

    In the below code, you can click on the set cookies button to set cookies. After that, click on the get cookies button to observe the cookies.

    Next, click the delete cookies button, and again get cookies to check whether the cookies are deleted.

    Here, we delete the data1 cookie only.

    <html><body><button onclick ="setCookies()"> Set Cookie </button><button onclick ="deleteCookies()"> Delete Cookie </button><button onclick="readCookies()"> Read Cookies </button><p id ="output"></p><script>let output = document.getElementById("output");functionsetCookies(){
    		document.cookie ="data1=test1;";
    		document.cookie ="data2=test2;";}functiondeleteCookies(){
    		document.cookie ="data1=test1;expires=Tue, 22 Aug 2023 12:00:00 UTC;";
    		document.cookie ="data2=test2;expires=Mon, 22 Aug 2050 12:00:00 UTC;";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    		output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="data1"|| key =="data2"){
    
    			output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Delete Cookies using 'max-age' Attribute

    The browser automatically deletes the cookie when you assign 0 or a negative value to the 'maxAge' attribute.

    Syntax

    Follow the syntax below to use the max-age attribute to delete the cookie.

    document.cookie ="user1=sam;max-age=-60;";

    In the above syntax, we have set a negative value to the 'max-age' attribute to delete the cookies.

    Example

    In the below code, we delete the user1 cookie only in the deleteCookies() function.

    <html><body><button onclick ="setCookies()"> Set Cookie </button><button onclick ="deleteCookies()"> Delete Cookie </button><button onclick ="readCookies()"> Read Cookies </button><p id ="output"></p><script>let output = document.getElementById("output");functionsetCookies(){
    		document.cookie ="user1=sam;";
    		document.cookie ="user2=virat;";}functiondeleteCookies(){
    		document.cookie ="user1=sam;max-age=-60;";
    		document.cookie ="user2=virat;max-age=5000;";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    		output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="user1"|| key =="user2"){
    
    			output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Delete Cookies Explicitly from the Browser

    You can manually delete the cookies from the browser by following the steps below.

    Step 1 − In your browser, click on the three verticle dots at the top right corner. After that, hover over the 'history, and it will open the menu. In the menu, click on the 'history.

    Delete Cookies Step 1

    Step 2 − Here, click on the 'clear browsing data' tab.

    Delete Cookies Step 2

    Step 3 − Check the cookies and other site data check boxes here. After that, click on the 'clear data' button.

    Delete Cookies Step 3

    However, the steps might differ based on what browser you are using.

    This way, you can use any way among the three to clear your browser's cookie.

  • Cookie Attributes

    Cookie Attributes

    The JavaScript cookie attributes are used to set additional information about a cookie such as path, domain, expiry date, etc. In JavaScript, you can specify the cookie attributes while setting up a new cookie or updating the cookie. For example, you can set the cookie’s expiry date using the ‘expires’ attributes.

    In simple terms, cookie attributes are used to control the behavior of the cookies and how the cookie is used in the browser.

    Here, we have listed all cookie attributes in the table below with its description.

    AttributeDescriptionDefault Value
    Name/ValueIt is used to store the cookies in the browser.
    DomainTo specify the domain for whose cookie is valid.Website of domain. For example, tutorialspoint.com
    PathThe path to the directory or web page that sets the cookie./ (entire domain)
    ExpiresIt is used to specify the date and time when the cookie should expire.Current session
    Max-AgeIt is used to specify the time limit after that cookie should expire.Current session
    SecureIf this field contains the word “secure”, then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.false
    HttpOnlyIt prevents accessing the cookies via JavaScript to make cookies secure.false
    SameSiteIt is used to specify how third-party cookies should be handled.Lax
    PriorityIt defines the priority of the cookies.1000
    Site/ServiceTo get information about the origin site of the cookie.
    SourcePortTo get the port of the source for the cookie.
    StoragePartitionIt defines which storage partition is used to store cookies.
    SizeIt represents the size of the cookies.The size depends on the text length.

    However, above all, attributes are optional.

    Also, you can’t manipulate all attributes of the cookies. The browser sets some attributes.

    Check the Attribute Value in the Browser

    You can set the attributes to the cookie, but you can’t access the attributes. To check whether the attribute is set, you can use the browser console.

    Follow the steps below to check cookies in the browser console.

    Step 1 − Right click in the browser. It will open the menu. You need to select the ‘inspect’ option. It will open the developer tool.

    Cookie Attributes Step 1

    Step 2 − After that, you need to go to the Application/ Storage tab.

    Cookie Attributes Step 2

    Step 3 − In the sidebar, select ‘cookies.

    Cookie Attributes Step 3

    Step 4 − Now, click on any cookies to check their name, value, and other attribute values.

    Cookie Attributes Step 4

    The above steps are only for the Chrome web browser. The step can differ according to what browser you are using.

    Here, you will learn each attribute one by one with examples.

    Cookie’s Name/Value Attribute

    The Name attribute is used to store the cookie data. It takes the data as a value. If you want to use the special characters in the value of the ‘Name’ attribute, you need to encode the text using the encodeURIComponent() method.

    Syntax

    Follow the syntax below to set the Name attribute of the cookie.

    let value =encodeURIComponent(cookieValue);
    document.cookie ="name="+ value +";";

    In the above syntax, we have encoded the ‘cookieValue’ using the encodeURIComponent() method and used the encoded value as a name attribute value.

    Example

    In the below code, we set the ‘subscribed’ cookie with a ‘false’ value. You can click the read cookies button to get the cookies.

    <html><body><p id ="output"></p><button onclick ="setCookies()"> Set Cookie </button><br><br><button onclick ="readCookies()"> Read Cookies </button><script>let output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="subscribed=false";// name-value pair
    			output.innerHTML ="Cookie setting successful!";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The subscribed cookie is - <br>";for(const cookie of allCookies){const[name, value]= cookie.split("=");if(name =="subscribed"){
    
    				output.innerHTML +=${name} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Cookie's Path Attribute

    The Path attribute is used to set the scope of the cookie. It defines where cookies should be accessible on the website. You may set the relative or absolute path as a Path attribute value.

    If you set the relative path, all the cookies can be accessible everywhere in the particular or sub-directory.

    Syntax

    Follow the syntax below to set the Path attribute in the cookie.

    document.cookie ="name=value;path=pathStr";

    In the above syntax, you need to replace the 'pathStr' with the actual path string.

    Example

    In the below code, we set the path for the cookie. Here, we set the / (home route). So, cookies can be accessible on each webpage of the website. You may try to get the cookie on the different web pages of the website.

    <html><body><button onclick ="setCookies()"> Set Cookie </button><p id ="output"></p><button onclick ="readCookies()"> Read Cookies </button><script>let output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="signIn=true; path=/";
    			output.innerHTML ="Cookie set successful!";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="signIn"){
    
    				output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Cookie Expires Attribute

    The 'expires' attribute is used to set the expiry date for the cookie. It takes the date string as a value.

    If you set 0 or past date as a value of the 'expires, the browser will automatically delete the cookie.

    Syntax

    Follow the syntax below to set the expires attribute in the cookie.

    document.cookie ="name=value;expires=dateStr";

    In the above syntax, you need to replace the 'dateStr' with the date string.

    Example

    In the code below, we set the product cookie. Also, we set the expiry date in 2050.

    You may try to set the past expiry date and try to access the cookie. You won't be able to find the cookie.

    <html><body><p id ="output"></p><button onclick ="setCookies()"> Set Cookie </button><br><br><button onclick ="readCookies()"> Read Cookies </button><script>let output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="product=mobile;expires=12 Jan 2050 12:00:00 UTC";
    			output.innerHTML ="Cookie Set Successful!";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="product"){
    
    				output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Cookie's maxAge Attribute

    The 'maxAge' attribute is an alternative to the 'expires' attribute. It is used to specify the lifetime of the cookie. It takes the seconds as a value.

    When the lifetime of the cookie is finished, it will automatically get deleted.

    Syntax

    Follow the syntax below to pass the 'maxAge' attribute to the cookie.

    document.cookie ="name=value;max-ge=age;";

    In the above syntax, you need to replace the 'age' with the number of seconds.

    Example

    In the below code, we set the total number of seconds equal to 10 days as a value of the maxAge attribute. You can set the lifetime of 1 second for the cookie and try to access the cookie after 1 second.

    <html><body><button onclick ="setCookies()"> Set Cookie </button><button onclick ="readCookies()"> Read Cookies </button><p id ="output"></p><script>const output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="token=1234wfijdn;max-age=864000";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="token"){
    
    				output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Cookie Domain Attribute

    The domain attribute is used to specify the domain for which the cookie is valid. The default value of the domain from which you are making a request. You may set the domain attribute to set the subdomains.

    Syntax

    Follow the syntax below to set the value of the domain attribute in the cookie.

    document.cookie ="name=value;domain:domain_name ";

    In the above syntax, replace the 'domain_name' with the actual domain, like example.com.

    Example

    In the below code, we set the 'tutorialspoint.com' domain for the cookie.

    <html><body><p id ="output"></p><button onclick ="setCookies()"> Set Cookie </button><button onclick ="readCookies()"> Read Cookies </button><script>const output = document.getElementById("output");functionsetCookies(){
    			document.cookie ="username=abcd;domain:tutorialspoint.com";}functionreadCookies(){const allCookies = document.cookie.split("; ");
    			output.innerHTML ="The cookie is : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="username"){
    
    				output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Similarly, you can also update the attribute values. For example, you can extend the expiry time of the cookie.

  • Cookies

    What are Cookies ?

    In JavaScript, cookies are piece of data stored in the user’s web browser. The cookies are stored in the key-value pair inside the browser. We can manipulate the cookies using cookie property of document object. We can set or store a cookie in key-value pair using the cookie property. We can read cookies using document’s cookie property and extract the desired information using destructuring.

    Why are Cookies needed?

    Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages.

    For example, you have logged in to a particular website on a particular web page. How do other webpages of the same website know your state that you have already completed the logged-in process? In this case, cookies are used.

    In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.

    Sometimes, cookies are also used for caching, increasing the website or application performance.

    How It Works ?

    Your server sends some data to the visitor’s browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor’s hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.

    Cookies are a plain text data record of 5 variable-length fields −

    • Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
    • Domain − The domain name of your site.
    • Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
    • Secure − If this field contains the word “secure”, then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
    • Name=Value − Cookies are set and retrieved in the form of key-value pairs

    Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client.

    Setting/ Storing Cookies

    JavaScript can manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.

    The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this.

    document.cookie ="key1 = value1;key2 = value2;expires = date";

    Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies’ value will not be accessible.

    The cookie string contains the key-value pairs separated by the semi-colons.

    Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value.

    Example

    Try the following. It sets a customer name in an input cookie.

    <html><head><script type ="text/javascript">functionWriteCookie(){if( document.myform.customer.value ==""){alert("Enter some value!");return;}
    
            cookievalue =escape(document.myform.customer.value)+";";
            document.cookie ="name="+ cookievalue;
            document.write("Setting Cookies : "+"name="+ cookievalue );}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;form name ="myform" action =""&gt;
         Enter name:&lt;input type ="text" name ="customer"/&gt;&lt;input type ="button" value ="Set Cookie" onclick ="WriteCookie();"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    https://www.tutorialspoint.com/javascript/src/write_cookie.htm

    Now your machine has a cookie called name. You can set multiple cookies using multiple key = value pairs separated by comma.

    Reading Cookies

    Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value.

    You can use strings' split() function to break a string into key and values as follows −

    Example

    Try the following example to get all the cookies.

    <html><head><script type ="text/javascript">functionReadCookie(){var allcookies = document.cookie;
    
            document.write("All Cookies : "+ allcookies );// Get all the cookies pairs in an array
            cookiearray = allcookies.split(';');// Now take key value pair out of this arrayfor(var i=0; i&lt;cookiearray.length; i++){
               name = cookiearray[i].split('=')[0];
               value = cookiearray[i].split('=')[1];
               document.write("Key is : "+ name +" and Value is : "+ value);}}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;form name ="myform" action =""&gt;&lt;p&gt; click the following button and see the result:&lt;/p&gt;&lt;input type ="button" value ="Get Cookie" onclick ="ReadCookie()"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Note − Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that time, please try to digest it.https://www.tutorialspoint.com/javascript/src/reading_cookies.htm

    Note − There may be some other cookies already set on your machine. The above code will display all the cookies set on your machine.

    Setting Cookies Expiry Date

    You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the expires attribute to a date and time.

    Example

    Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.

    <html><head><script type ="text/javascript">functionWriteCookie(){var now =newDate();
    
            now.setMonth( now.getMonth()+1);
            cookievalue =escape(document.myform.customer.value)+";"
            
            document.cookie ="name="+ cookievalue;
            document.cookie ="expires="+ now.toUTCString()+";"
            document.write("Setting Cookies : "+"name="+ cookievalue );}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;form name ="myform" action =""&gt;
         Enter name:&lt;input type ="text" name ="customer"/&gt;&lt;input type ="button" value ="Set Cookie" onclick ="WriteCookie()"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    https://www.tutorialspoint.com/javascript/src/setting_cookies.htm

    Deleting a Cookie

    Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiry date to a time in the past.

    Example

    Try the following example. It illustrates how to delete a cookie by setting its expiry date to one month behind the current date.

    <html><head><script type ="text/javascript">functionWriteCookie(){var now =newDate();
    
            now.setMonth( now.getMonth()-1);
            cookievalue =escape(document.myform.customer.value)+";"
               
            document.cookie ="name="+ cookievalue;
            document.cookie ="expires="+ now.toUTCString()+";"
            document.write("Setting Cookies : "+"name="+ cookievalue );}&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;form name ="myform" action =""&gt;
         Enter name:&lt;input type ="text" name ="customer"/&gt;&lt;input type ="button" value ="Set Cookie" onclick ="WriteCookie()"/&gt;&lt;/form&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Output

    https://www.tutorialspoint.com/javascript/src/deleting_cookies.htm

    Updating Cookies

    To update the particular key-value pair in the cookie, you can assign new key-value pair to the document.cookie property. Here, you need to ensure you are using the same key whose value you want to update.

    Syntax

    Follow the syntax below to update the cookies.

    document.cookie="key1=value1";

    In the above syntax, we are updating the value of the key cookie.

    Example

    In the code below, click the set cookies button to set the cookies. It will set the watch value for the cartItem and 10000 for the price.

    After that, you can click the get cookies button to observe the cookies.

    Next, you can click on the update cookies button to update the cookies. It will change the cartItem value to bag and the price to 5000.

    Now, click the get cookies button again to get the updated cookie value.

    <html><body><p id ="output"></p><button onclick ="setCookies()"> Set Cookie </button><br><br><button onclick ="updateCookies()"> Update Cookie </button><br><br><button onclick ="getCookies()"> Get Cookies </button><script>let output = document.getElementById("output");functionsetCookies(){
      document.cookie ="cartItem=watch";
      document.cookie ="price=10000";}functionupdateCookies(){// Updating cookies
      document.cookie ="cartItem=bag"; 
      document.cookie ="price=5000";}functiongetCookies(){//Spliting the cookie stringconst allCookies = document.cookie.split("; "); 
      output.innerHTML ="The cookie data are : <br>";for(const cookie of allCookies){const[key, value]= cookie.split("=");if(key =="cartItem"|| key =="price"){
    
       output.innerHTML +=${key} : ${decodeURIComponent(value)} &amp;lt;br&amp;gt;;}}}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>