Cookie.hx 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package js;
  2. class Cookie {
  3. /**
  4. Create or update a cookie.
  5. expireDelay (seconds), if null, the cookie expires at end of session
  6. **/
  7. public static function set( name : String, value : String, ?expireDelay : Int, ?path : String, ?domain : String ){
  8. var s = name+"="+StringTools.urlEncode(value);
  9. if( expireDelay != null ){
  10. var d = DateTools.delta(Date.now(),expireDelay*1000);
  11. s += ";expires=" + untyped d.toGMTString();
  12. }
  13. if( path != null ){
  14. s += ";path="+path;
  15. }
  16. if( domain != null ){
  17. s += ";domain="+domain;
  18. }
  19. js.Lib.document.cookie = s;
  20. }
  21. /**
  22. Returns all cookies
  23. **/
  24. public static function all(){
  25. var h = new Hash();
  26. var a = js.Lib.document.cookie.split(";");
  27. for( e in a ){
  28. e = StringTools.ltrim(e);
  29. var t = e.split("=");
  30. if( t.length < 2 )
  31. continue;
  32. h.set(t[0],StringTools.urlDecode(t[1]));
  33. }
  34. return h;
  35. }
  36. /**
  37. Returns value of a cookie.
  38. **/
  39. public static function get( name : String ){
  40. return all().get(name);
  41. }
  42. /**
  43. Returns true if a cookie [name] exists
  44. **/
  45. public static function exists( name : String ){
  46. return all().exists(name);
  47. }
  48. /**
  49. Remove a cookie
  50. **/
  51. public static function remove( name : String, ?path : String, ?domain : String ){
  52. set(name,"",-10,path,domain);
  53. }
  54. }