jquery.cookie.js 2.4 KB

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