Setting, getting and deleting cookies using Javascript


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function setCookie (name, value, expires, path, domain, secure){
  2. var today = new Date();
  3. today.setTime(today.getTime());
  4. if (expires){
  5. expires = expires * 1000 * 60 * 60 * 24;
  6. }
  7. var expires_date = new Date( today.getTime() + (expires));
  8. document.cookie = name+'='+escape( value ) +
  9. ((expires) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
  10. ((path) ? ';path=' + path : '' ) +
  11. ((domain) ? ';domain=' + domain : '' ) +
  12. ((secure) ? ';secure' : '' );
  13. }
  14.  
  15. function getCookie(name){
  16. var start = document.cookie.indexOf( name + "=" );
  17. var len = start + name.length + 1;
  18. if ((!start) && (name != document.cookie.substring( 0, name.length))){
  19. return null;
  20. }
  21. if (start == -1) return null;
  22. var end = document.cookie.indexOf(';', len);
  23. if (end == -1) end = document.cookie.length;
  24. return unescape(document.cookie.substring(len, end));
  25. }
  26.  
  27. function deleteCookie (name, path, domain){
  28. if (getCookie(name)) document.cookie = name + '=' +
  29. ((path) ? ';path=' + path : '') +
  30. ((domain) ? ';domain=' + domain : '' ) +
  31. ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
  32. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.