Posted By

enchance on 09/06/09


Tagged

cookies


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

sulfurito
guido


Cookies


 / Published in: JavaScript
 

  1. function cookiesAllowed() {
  2. setCookie('checkCookie', 'test', 1);
  3. if (getCookie('checkCookie')) {
  4. deleteCookie('checkCookie');
  5. return true;
  6. }
  7. return false;
  8. }
  9.  
  10. function setCookie(name,value,expires, options) {
  11. if (options===undefined) { options = {}; }
  12. if ( expires ) {
  13. var expires_date = new Date();
  14. expires_date.setDate(expires_date.getDate() + expires)
  15. }
  16. document.cookie = name+'='+escape( value ) +
  17. ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) +
  18. ( ( options.path ) ? ';path=' + options.path : '' ) +
  19. ( ( options.domain ) ? ';domain=' + options.domain : '' ) +
  20. ( ( options.secure ) ? ';secure' : '' );
  21. }
  22.  
  23. function getCookie( name ) {
  24. var start = document.cookie.indexOf( name + "=" );
  25. var len = start + name.length + 1;
  26. if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
  27. return null;
  28. }
  29. if ( start == -1 ) return null;
  30. var end = document.cookie.indexOf( ';', len );
  31. if ( end == -1 ) end = document.cookie.length;
  32. return unescape( document.cookie.substring( len, end ) );
  33. }
  34.  
  35. function deleteCookie( name, path, domain ) {
  36. if ( getCookie( name ) ) document.cookie = name + '=' +
  37. ( ( path ) ? ';path=' + path : '') +
  38. ( ( domain ) ? ';domain=' + domain : '' ) +
  39. ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
  40. }
  41.  
  42.  
  43. // Usage:
  44. // Check if cookies are allowed in this browser.
  45. if cookiesAllowed() {
  46. alert('you can set cookies');
  47. } else {
  48. alert("This browser doesn't allow cookies.");
  49. }
  50.  
  51. // Create a cookie named myCookie with a value of 'Peanut Butter'
  52. // The cookie will expire in 10 days.
  53. setCookie('myCookie','Peanut Butter', 10);
  54.  
  55. // Retreive the value of 'myCookie'
  56. var userCookie = getCookie('myCookie');
  57.  
  58. // Delete 'myCookie'
  59. deleteCookie('myCookie');

Report this snippet  

You need to login to post a comment.