Set Cookie and Get Cookie with Javascript

Set cookie and get cookie with JavaScript

Working with cookies is a common task when developing web applications. Cookies are small pieces of data that are stored on the user’s browser. They can be used to remember user preferences, track user activity, and more. In JavaScript, there are built-in methods for setting and getting cookies. In this blog post, we will explore how to set a cookie and retrieve its value using JavaScript.

Setting a cookie

To set a cookie in JavaScript, you can use the document.cookie property. This property allows you to read and write cookies. To set a cookie, you need to assign a string value to document.cookie in the following format:

document.cookie = "cookieName=cookieValue; expires=expiryDate; path=pathValue";

Let’s break down the components of the cookie string:

  • cookieName: The name of the cookie.
  • cookieValue: The value of the cookie.
  • expires: The expiry date of the cookie. If not specified, the cookie will be deleted when the browser is closed.
  • path: The path on the server where the cookie is valid. If not specified, the cookie will be valid for the current page.

Here’s an example of setting a cookie:

// Set a cookie with name "username" and value "John Doe"
document.cookie = "username=John Doe";

Getting a cookie

To retrieve the value of a cookie, you can use the document.cookie property. However, the document.cookie property returns all the cookies as a single string. To extract the value of a specific cookie, you need to parse the string. Here’s an example:

function getCookie(cookieName) {
  var name = cookieName + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var cookieArray = decodedCookie.split(';');
  
  for(var i = 0; i < cookieArray.length; i++) {
    var cookie = cookieArray[i];
    
    while (cookie.charAt(0) === ' ') {
      cookie = cookie.substring(1);
    }
    
    if (cookie.indexOf(name) === 0) {
      return cookie.substring(name.length, cookie.length);
    }
  }
  
  return "";
}

// Get the value of the cookie named "username"
var username = getCookie("username");
console.log(username); // Output: John Doe

In the getCookie function above, we first decode the cookie string using decodeURIComponent. Then, we split the string into an array of cookies using the ';' separator. We iterate over the array and extract the value of the cookie that matches the specified name.

By using the document.cookie property and the getCookie function, you can easily set and retrieve cookies in JavaScript.

Remember to handle cookie values securely and be mindful of any privacy concerns when working with cookies.

Final Output:

<

pre>

Set cookie and get cookie with JavaScript Working with cookies is a common task when developing web applications. Cookies are small pieces of data that are stored on the user's browser. They can be used to remember user preferences, track user activity, and more. In JavaScript, there are built-in methods for setting and getting cookies. In this blog post, we will explore how to set a cookie and retrieve its value using JavaScript. Setting a cookie To set a cookie in JavaScript, you can use the document.cookie property. This property allows you to read and write cookies. To set a cookie, you need to assign a string value to document.cookie in the following format: document.cookie = "cookieName=cookieValue; expires=expiryDate; path=pathValue"; Let's break down the components of the cookie string: cookieName: The name of the cookie. cookieValue: The value of the cookie. expires: The expiry date of the cookie. If not specified, the cookie will be deleted when the browser is closed. path: The path on the server where the cookie is valid. If not specified, the cookie will be valid for the current page. Here's an example of setting a cookie: < pre>// Set a cookie with name "username" and value "John Doe Share this:FacebookX Related Posts: How Do I Set/Unset a Cookie with Jquery? How do I set/unset a cookie with jQuery? Working with cookies in JavaScript can be a bit tricky, but with... Accessing Nested Javascript Objects and Arrays by String Path When working with JavaScript, it is common to come across situations where you need to access nested objects and arrays... Is Safari on Ios 6 Caching $.Ajax Results? Is Safari on iOS 6 caching $.ajax results? As a tech professional working with JavaScript, you may have encountered the... How to Check If a String Is a Valid Json String? How to check if a string is a valid JSON string? When working with JavaScript, you might come across scenarios...
Posted September 10, 2023 in Common Problems, JavaScript, Uncategorized by Nikolas H. Tags: Comments Leave a Reply Cancel replyYour email address will not be published. Required fields are marked *Comment * Name * Email * Website Save my name, email, and website in this browser for the next time I comment.
JS Duck Privacy Policy © Copyright 2023
window.WPCOM_sharing_counts = {"https:\/\/js-duck.com\/set-cookie-and-get-cookie-with-javascript-2\/":1267}; var ce4wp_form_submit_data = {"siteUrl":"https:\/\/js-duck.com","url":"https:\/\/js-duck.com\/wp-admin\/admin-ajax.php","nonce":"aead8153ea","listNonce":"e4be718877","activatedNonce":"564eca04a5"}; ( function() { var skipLinkTarget = document.querySelector( 'main' ), sibling, skipLinkTargetID, skipLink; // Early exit if a skip-link target can't be located. if ( ! skipLinkTarget ) { return; } /* * Get the site wrapper. * The skip-link will be injected in the beginning of it. */ sibling = document.querySelector( '.wp-site-blocks' ); // Early exit if the root element was not found. if ( ! sibling ) { return; } // Get the skip-link target's ID, and generate one if it doesn't exist. skipLinkTargetID = skipLinkTarget.id; if ( ! skipLinkTargetID ) { skipLinkTargetID = 'wp--skip-link--target'; skipLinkTarget.id = skipLinkTargetID; } // Create the skip link. skipLink = document.createElement( 'a' ); skipLink.classList.add( 'skip-link', 'screen-reader-text' ); skipLink.href = '#' + skipLinkTargetID; skipLink.innerHTML = 'Skip to content'; // Inject the skip link. sibling.parentElement.insertBefore( skipLink, sibling ); }() ); var hcbVars = {"showCopyBtn":"1","copyBtnLabel":"Copy code to clipboard"}; _stq = window._stq || []; _stq.push([ "view", JSON.parse("{\"v\":\"ext\",\"blog\":\"223076394\",\"post\":\"1267\",\"tz\":\"0\",\"srv\":\"js-duck.com\",\"j\":\"1:14.5\"}") ]); _stq.push([ "clickTrackerInit", "223076394", "1267" ]); wp.i18n.setLocaleData( { 'text direction\u0004ltr': [ 'ltr' ] } ); var _wpUtilSettings = {"ajax":{"url":"\/wp-admin\/admin-ajax.php"}}; var dracula = {"homeUrl":"https:\/\/js-duck.com","ajaxUrl":"https:\/\/js-duck.com\/wp-admin\/admin-ajax.php","pluginUrl":"https:\/\/js-duck.com\/wp-content\/plugins\/dracula-dark-mode","settings":{"excludes":[""],"colorMode":"presets","preset":"dracula"},"isPro":"","upgradeUrl":"https:\/\/js-duck.com\/wp-admin\/admin.php?billing_cycle=annual&page=dracula-pricing","nonce":"5cfc397618"}; var sharing_js_options = {"lang":"en","counts":"1","is_stats_active":"1"}; var windowOpen; ( function () { function matches( el, sel ) { return !! ( el.matches && el.matches( sel ) || el.msMatchesSelector && el.msMatchesSelector( sel ) ); } document.body.addEventListener( 'click', function ( event ) { if ( ! event.target ) { return; } var el; if ( matches( event.target, 'a.share-facebook' ) ) { el = event.target; } else if ( event.target.parentNode && matches( event.target.parentNode, 'a.share-facebook' ) ) { el = event.target.parentNode; } if ( el ) { event.preventDefault(); // If there's another sharing window open, close it. if ( typeof windowOpen !== 'undefined' ) { windowOpen.close(); } windowOpen = window.open( el.getAttribute( 'href' ), 'wpcomfacebook', 'menubar=1,resizable=1,width=600,height=400' ); return false; } } ); } )(); var windowOpen; ( function () { function matches( el, sel ) { return !! ( el.matches && el.matches( sel ) || el.msMatchesSelector && el.msMatchesSelector( sel ) ); } document.body.addEventListener( 'click', function ( event ) { if ( ! event.target ) { return; } var el; if ( matches( event.target, 'a.share-x' ) ) { el = event.target; } else if ( event.target.parentNode && matches( event.target.parentNode, 'a.share-x' ) ) { el = event.target.parentNode; } if ( el ) { event.preventDefault(); // If there's another sharing window open, close it. if ( typeof windowOpen !== 'undefined' ) { windowOpen.close(); } windowOpen = window.open( el.getAttribute( 'href' ), 'wpcomx', 'menubar=1,resizable=1,width=600,height=350' ); return false; } } ); } )();