jquery.cookie.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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) {
  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. try {
  30. return config.json ? JSON.parse(s) : s;
  31. } catch(er) {}
  32. }
  33. var config = $.cookie = function (key, value, options) {
  34. // write
  35. if (value !== undefined) {
  36. options = $.extend({}, config.defaults, options);
  37. if (typeof options.expires === 'number') {
  38. var days = options.expires, t = options.expires = new Date();
  39. t.setDate(t.getDate() + days);
  40. }
  41. value = config.json ? JSON.stringify(value) : String(value);
  42. return (document.cookie = [
  43. config.raw ? key : encodeURIComponent(key),
  44. '=',
  45. config.raw ? value : encodeURIComponent(value),
  46. options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
  47. options.path ? '; path=' + options.path : '',
  48. options.domain ? '; domain=' + options.domain : '',
  49. options.secure ? '; secure' : ''
  50. ].join(''));
  51. }
  52. // read
  53. var decode = config.raw ? raw : decoded;
  54. var cookies = document.cookie.split('; ');
  55. var result = key ? undefined : {};
  56. for (var i = 0, l = cookies.length; i < l; i++) {
  57. var parts = cookies[i].split('=');
  58. var name = decode(parts.shift());
  59. var cookie = decode(parts.join('='));
  60. if (key && key === name) {
  61. result = converted(cookie);
  62. break;
  63. }
  64. if (!key) {
  65. result[name] = converted(cookie);
  66. }
  67. }
  68. return result;
  69. };
  70. config.defaults = {};
  71. $.removeCookie = function (key, options) {
  72. if ($.cookie(key) !== undefined) {
  73. // Must not alter options, thus extending a fresh object...
  74. $.cookie(key, '', $.extend({}, options, { expires: -1 }));
  75. return true;
  76. }
  77. return false;
  78. };
  79. }));