jquery.cookie.js 2.2 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 (factory) {
  9. if (typeof define === 'function' && define.amd && define.amd.jQuery) {
  10. // AMD. Register as anonymous module.
  11. define(['jquery'], factory);
  12. } else {
  13. // Browser globals.
  14. factory(jQuery);
  15. }
  16. }(function ($) {
  17. var pluses = /\+/g;
  18. function raw(s) {
  19. return s;
  20. }
  21. function decoded(s) {
  22. return decodeURIComponent(s.replace(pluses, ' '));
  23. }
  24. function converted(s) {
  25. if (s.indexOf('"') === 0) {
  26. // This is a quoted cookie as according to RFC2068, unescape
  27. s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
  28. }
  29. return config.json ? JSON.parse(s) : s;
  30. }
  31. var config = $.cookie = function (key, value, options) {
  32. // write
  33. if (value !== undefined) {
  34. options = $.extend({}, config.defaults, options);
  35. if (typeof options.expires === 'number') {
  36. var days = options.expires, t = options.expires = new Date();
  37. t.setDate(t.getDate() + days);
  38. }
  39. value = config.json ? JSON.stringify(value) : String(value);
  40. return (document.cookie = [
  41. encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value),
  42. options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
  43. options.path ? '; path=' + options.path : '',
  44. options.domain ? '; domain=' + options.domain : '',
  45. options.secure ? '; secure' : ''
  46. ].join(''));
  47. }
  48. // read
  49. var decode = config.raw ? raw : decoded;
  50. var cookies = document.cookie.split('; ');
  51. var result = key ? undefined : {};
  52. for (var i = 0, l = cookies.length; i < l; i++) {
  53. var parts = cookies[i].split('=');
  54. var name = decode(parts.shift());
  55. var cookie = decode(parts.join('='));
  56. if (key && key === name) {
  57. result = converted(cookie);
  58. break;
  59. }
  60. if (!key) {
  61. result[name] = converted(cookie);
  62. }
  63. }
  64. return result;
  65. };
  66. config.defaults = {};
  67. $.removeCookie = function (key, options) {
  68. if ($.cookie(key) !== undefined) {
  69. $.cookie(key, '', $.extend(options, { expires: -1 }));
  70. return true;
  71. }
  72. return false;
  73. };
  74. }));