jquery.cookies.js 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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($, document) {
  12. var pluses = /\+/g;
  13. function raw(s) {
  14. return s;
  15. }
  16. function decoded(s) {
  17. return decodeURIComponent(s.replace(pluses, ' '));
  18. }
  19. $.cookie = function(key, value, options) {
  20. // key and at least value given, set cookie...
  21. if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value == null)) {
  22. options = $.extend({}, $.cookie.defaults, options);
  23. if (value == null) {
  24. options.expires = -1;
  25. }
  26. if (typeof options.expires === 'number') {
  27. var days = options.expires, t = options.expires = new Date();
  28. t.setDate(t.getDate() + days);
  29. }
  30. value = String(value);
  31. return (document.cookie = [
  32. encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
  33. options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
  34. options.path ? '; path=' + options.path : '',
  35. options.domain ? '; domain=' + options.domain : '',
  36. options.secure ? '; secure' : ''
  37. ].join(''));
  38. }
  39. // key and possibly options given, get cookie...
  40. options = value || $.cookie.defaults || {};
  41. var decode = options.raw ? raw : decoded;
  42. var cookies = document.cookie.split('; ');
  43. for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
  44. if (decode(parts.shift()) === key) {
  45. return decode(parts.join('='));
  46. }
  47. }
  48. return null;
  49. };
  50. $.cookie.defaults = {};
  51. $.removeCookie = function (key, options) {
  52. if ($.cookie(key) !== undefined) {
  53. // Must not alter options, thus extending a fresh object...
  54. $.cookie(key, '', $.extend({}, options, { expires: -1 }));
  55. return true;
  56. }
  57. return false;
  58. };
  59. })(jQuery, document);