jquery.cookie.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*jshint eqnull:true */
  2. /*!
  3. * jQuery Cookie Plugin v1.1
  4. * https://github.com/carhartl/jquery-cookie
  5. *
  6. * Copyright 2011, Klaus Hartl
  7. * Dual licensed under the MIT or GPL Version 2 licenses.
  8. * http://www.opensource.org/licenses/mit-license.php
  9. * http://www.opensource.org/licenses/GPL-2.0
  10. */
  11. (function (factory) {
  12. if (typeof define === 'function' && define.amd) {
  13. define(["jquery"], factory);
  14. } else {
  15. factory(jQuery);
  16. }
  17. }(function ($) {
  18. var pluses = /\+/g;
  19. function raw(s) {
  20. return s;
  21. }
  22. function decoded(s) {
  23. return decodeURIComponent(s.replace(pluses, ' '));
  24. }
  25. $.cookie = function(key, value, options) {
  26. // key and at least value given, set cookie...
  27. if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value == null)) {
  28. options = $.extend({}, $.cookie.defaults, options);
  29. if (value == null) {
  30. options.expires = -1;
  31. }
  32. if (typeof options.expires === 'number') {
  33. var days = options.expires, t = options.expires = new Date();
  34. t.setDate(t.getDate() + days);
  35. }
  36. value = String(value);
  37. return (document.cookie = [
  38. encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
  39. options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
  40. options.path ? '; path=' + options.path : '',
  41. options.domain ? '; domain=' + options.domain : '',
  42. options.secure ? '; secure' : ''
  43. ].join(''));
  44. }
  45. // key and possibly options given, get cookie...
  46. options = value || $.cookie.defaults || {};
  47. var decode = options.raw ? raw : decoded;
  48. var cookies = document.cookie.split('; ');
  49. for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
  50. if (decode(parts.shift()) === key) {
  51. return decode(parts.join('='));
  52. }
  53. }
  54. return null;
  55. };
  56. $.cookie.defaults = {};
  57. }));