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

damarev on 07/17/06


Tagged


Versions (?)


Who likes this?

8 people have marked this snippet as a favorite

luman
xaviaracil
meth
cochambre
nicolaspar
gbvb
vali29
SpinZ


javascript cookies


Published in: JavaScript 


  1. /**
  2.  * Sets a Cookie with the given name and value.
  3.  *
  4.  * name Name of the cookie
  5.  * value Value of the cookie
  6.  * [expires] Expiration date of the cookie (default: end of current session)
  7.  * [path] Path where the cookie is valid (default: path of calling document)
  8.  * [domain] Domain where the cookie is valid
  9.  * (default: domain of calling document)
  10.  * [secure] Boolean value indicating if the cookie transmission requires a
  11.  * secure transmission
  12.  */
  13. function setCookie(name, value, expires, path, domain, secure) {
  14. document.cookie= name + "=" + escape(value) +
  15. ((expires) ? "; expires=" + expires.toGMTString() : "") +
  16. ((path) ? "; path=" + path : "") +
  17. ((domain) ? "; domain=" + domain : "") +
  18. ((secure) ? "; secure" : "");
  19. }
  20.  
  21. /**
  22.  * Gets the value of the specified cookie.
  23.  *
  24.  * name Name of the desired cookie.
  25.  *
  26.  * Returns a string containing value of specified cookie,
  27.  * or null if cookie does not exist.
  28.  */
  29. function getCookie(name) {
  30. var dc = document.cookie;
  31. var prefix = name + "=";
  32. var begin = dc.indexOf("; " + prefix);
  33. if (begin == -1) {
  34. begin = dc.indexOf(prefix);
  35. if (begin != 0) return null;
  36. } else {
  37. begin += 2;
  38. }
  39. var end = document.cookie.indexOf(";", begin);
  40. if (end == -1) {
  41. end = dc.length;
  42. }
  43. return unescape(dc.substring(begin + prefix.length, end));
  44. }
  45.  
  46. /**
  47.  * Deletes the specified cookie.
  48.  *
  49.  * name name of the cookie
  50.  * [path] path of the cookie (must be same as path used to create cookie)
  51.  * [domain] domain of the cookie (must be same as domain used to create cookie)
  52.  */
  53. function deleteCookie(name, path, domain) {
  54. if (getCookie(name)) {
  55. document.cookie = name + "=" +
  56. ((path) ? "; path=" + path : "") +
  57. ((domain) ? "; domain=" + domain : "") +
  58. "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  59. }
  60. }

Report this snippet 

You need to login to post a comment.