jquery.cookie.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*!
  2. * jQuery Cookie Plugin v1.3.1
  3. * https://github.com/carhartl/jquery-cookie
  4. *
  5. * Copyright 2013 Klaus Hartl
  6. * Released under the MIT license
  7. */
  8. (function ($, document, undefined) {
  9. var pluses = /\+/g;
  10. function raw(s) {
  11. return s;
  12. }
  13. function decoded(s) {
  14. return unRfc2068(decodeURIComponent(s.replace(pluses, ' ')));
  15. }
  16. function unRfc2068(value) {
  17. if (value.indexOf('"') === 0) {
  18. // This is a quoted cookie as according to RFC2068, unescape
  19. value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
  20. }
  21. return value;
  22. }
  23. function fromJSON(value) {
  24. return config.json ? JSON.parse(value) : value;
  25. }
  26. var config = $.cookie = function (key, value, options) {
  27. // write
  28. if (value !== undefined) {
  29. options = $.extend({}, config.defaults, options);
  30. if (value === null) {
  31. options.expires = -1;
  32. }
  33. if (typeof options.expires === 'number') {
  34. var days = options.expires, t = options.expires = new Date();
  35. t.setDate(t.getDate() + days);
  36. }
  37. value = config.json ? JSON.stringify(value) : String(value);
  38. return (document.cookie = [
  39. encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value),
  40. options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
  41. options.path ? '; path=' + options.path : '',
  42. options.domain ? '; domain=' + options.domain : '',
  43. options.secure ? '; secure' : ''
  44. ].join(''));
  45. }
  46. // read
  47. var decode = config.raw ? raw : decoded;
  48. var cookies = document.cookie.split('; ');
  49. var result = key ? null : {};
  50. for (var i = 0, l = cookies.length; i < l; i++) {
  51. var parts = cookies[i].split('=');
  52. var name = decode(parts.shift());
  53. var cookie = decode(parts.join('='));
  54. if (key && key === name) {
  55. result = fromJSON(cookie);
  56. break;
  57. }
  58. if (!key) {
  59. result[name] = fromJSON(cookie);
  60. }
  61. }
  62. return result;
  63. };
  64. config.defaults = {};
  65. $.removeCookie = function (key, options) {
  66. if ($.cookie(key) !== null) {
  67. $.cookie(key, null, options);
  68. return true;
  69. }
  70. return false;
  71. };
  72. })(jQuery, document);