zepto.cookie.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Zepto.cookie plugin
  2. //
  3. // Copyright (c) 2010, 2012
  4. // @author Klaus Hartl (stilbuero.de)
  5. // @author Daniel Lacy (daniellacy.com)
  6. //
  7. // Dual licensed under the MIT and GPL licenses:
  8. // http://www.opensource.org/licenses/mit-license.php
  9. // http://www.gnu.org/licenses/gpl.html
  10. ;(function($){
  11. $.extend($.fn, {
  12. cookie : function (key, value, options) {
  13. var days, time, result, decode
  14. // A key and value were given. Set cookie.
  15. if (arguments.length > 1 && String(value) !== "[object Object]") {
  16. // Enforce object
  17. options = $.extend({}, options)
  18. if (value === null || value === undefined) options.expires = -1
  19. if (typeof options.expires === 'number') {
  20. days = (options.expires * 24 * 60 * 60 * 1000)
  21. time = options.expires = new Date()
  22. time.setTime(time.getTime() + days)
  23. }
  24. value = String(value)
  25. return (document.cookie = [
  26. encodeURIComponent(key), '=',
  27. options.raw ? value : encodeURIComponent(value),
  28. options.expires ? '; expires=' + options.expires.toUTCString() : '',
  29. options.path ? '; path=' + options.path : '',
  30. options.domain ? '; domain=' + options.domain : '',
  31. options.secure ? '; secure' : ''
  32. ].join(''))
  33. }
  34. // Key and possibly options given, get cookie
  35. options = value || {}
  36. decode = options.raw ? function (s) { return s } : decodeURIComponent
  37. return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null
  38. }
  39. })
  40. })(Zepto)