We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

gbot on 03/09/08


Tagged

cookies


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

gbot
jamesming


javascript get/set/del cookies


Published in: JavaScript 


URL: http://www.dustindiaz.com/top-ten-javascript/

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

Report this snippet 

You need to login to post a comment.