jquery.cookie.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*!
  2. * jQuery Cookie Plugin
  3. * https://github.com/carhartl/jquery-cookie
  4. *
  5. * Copyright 2011, Klaus Hartl
  6. * Dual licensed under the MIT or GPL Version 2 licenses.
  7. * http://www.opensource.org/licenses/mit-license.php
  8. * http://www.opensource.org/licenses/GPL-2.0
  9. */
  10. (function($) {
  11. $.cookie = function(key, value, options) {
  12. // key and at least value given, set cookie...
  13. if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) {
  14. options = $.extend({}, options);
  15. if (value === null || value === undefined) {
  16. options.expires = -1;
  17. }
  18. if (typeof options.expires === 'number') {
  19. var days = options.expires, t = options.expires = new Date();
  20. t.setDate(t.getDate() + days);
  21. }
  22. value = String(value);
  23. return (document.cookie = [
  24. encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
  25. options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
  26. options.path ? '; path=' + options.path : '',
  27. options.domain ? '; domain=' + options.domain : '',
  28. options.secure ? '; secure' : ''
  29. ].join(''));
  30. }
  31. // key and possibly options given, get cookie...
  32. options = value || {};
  33. var decode = options.raw ? function(s) { return s; } : decodeURIComponent;
  34. var pairs = document.cookie.split('; ');
  35. for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) {
  36. if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
  37. }
  38. return null;
  39. };
  40. })(jQuery);