Posted By

deanhouseholder on 03/12/14


Tagged

javascript cookie cookies


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Beppoi


JavaScript Cookie Functions


 / Published in: JavaScript
 

Simple functions to add, fetch or delete cookies in the browser via JavaScript.

  1. function setCookie(c_name,c_value,c_expiredays,c_path,c_domain) {
  2. var c_exdate=new Date();
  3. c_exdate.setDate(c_exdate.getDate()+c_expiredays);
  4. document.cookie=c_name+ "=" +escape(c_value)+((c_expiredays==null) ? "" : ";expires="+c_exdate.toUTCString()) +"; path="+ c_path +"; domain="+ c_domain;
  5. }
  6.  
  7. function getCookie(tag) {
  8. var value = null
  9. var myCookie = document.cookie + ";"
  10. var findTag = tag + "="
  11. var endPos
  12. if (myCookie.length > 0) {
  13. var beginPos = myCookie.indexOf(findTag)
  14. if (beginPos != -1) {
  15. beginPos = beginPos + findTag.length
  16. endPos = myCookie.indexOf(";",beginPos)
  17. if (endPos == -1)
  18. endPos = myCookie.length
  19. value = unescape(myCookie.substring(beginPos,endPos))
  20. }
  21. }
  22. return value
  23. }
  24.  
  25. function deleteCookie(cookie) {
  26. var yesterday = 24 * 60 * 60 * 1000
  27. var expireDate = new Date()
  28. expireDate.setTime (expireDate.getTime() - yesterday)
  29. document.cookie =cookie + "=" + escape("nothing") + ";" + "expires" + "=" + expireDate.toGMTString()
  30. }

Report this snippet  

You need to login to post a comment.