Get and Set Cookie


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



Copy this code and paste it in your HTML
  1. function Trim(strValue) {
  2. return strValue.replace(/^\s+|\s+$/g, '');
  3. }
  4.  
  5. function getCookie(key) {
  6. var result = false;
  7. if(document.cookie) {
  8. var mycookieArray = document.cookie.split(';');
  9. for(i=0; i<mycookieArray.length; i++) {
  10. var mykeyValue = mycookieArray[i].split('=');
  11. if(Trim(mykeyValue[0]) == key) result = mykeyValue[1];
  12. }
  13. }
  14. return result;
  15. }
  16.  
  17. function setCookie(key, value, hoursExpire) {
  18. var ablauf = new Date();
  19. var expireTime = ablauf.getTime() + (hoursExpire * 60 * 60 * 1000);
  20. ablauf.setTime(expireTime);
  21. document.cookie = key + "=" + value + "; expires=" + ablauf.toGMTString();
  22. }
  23.  
  24. var mycookie = getCookie('meincookie');
  25. if(!mycookie) {
  26. // do whatever you want if the cookie is not set
  27. setCookie('meincookie', 'true', 24);
  28. } else {
  29. // do whatever you want if the cookie is set
  30. // mycookie contains the cookie value
  31. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.