Skip to content

Instantly share code, notes, and snippets.

@aslamdoctor
Created February 20, 2024 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aslamdoctor/7d66d566f05a018eb87d63ad0c9a7a22 to your computer and use it in GitHub Desktop.
Save aslamdoctor/7d66d566f05a018eb87d63ad0c9a7a22 to your computer and use it in GitHub Desktop.
Javascript Cookie Helper
// Cookie helper functions
const CookieHelper = {
/**
* Set Cookie.
*
* @param {string} name
* @param {string} value
* @param {string} minutes
*/
setCookie( name, value, minutes ) {
let expires = '';
if ( minutes ) {
const now = new Date();
expires = '; expires=' + new Date(now.getTime() + minutes * 60000);
}
document.cookie = name + '=' + ( value || '' ) + expires + ';';
},
/**
* Get Cookie.
*
* @param {string} name
* @return {string} null
*/
getCookie( name ) {
const cookies = document.cookie.split( ';' );
for ( const cookie of cookies ) {
if ( -1 < cookie.indexOf( name + '=' ) ) {
return cookie.split( '=' )[ 1 ];
}
}
return null;
},
/**
* Delete Cookie.
*
* @param {string} name
* @return {string} null
*/
deleteCookie( name ) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment