1.代码

  1. ;(function (factory) {
  2. var registeredInModuleLoader;
  3. if (typeof define === 'function' && define.amd) {
  4. define(factory);
  5. registeredInModuleLoader = true;
  6. }
  7. if (typeof exports === 'object') {
  8. module.exports = factory();
  9. registeredInModuleLoader = true;
  10. }
  11. if (!registeredInModuleLoader) {
  12. var OldCookies = window.Cookies;
  13. var api = window.Cookies = factory();
  14. api.noConflict = function () {
  15. window.Cookies = OldCookies;
  16. return api;
  17. };
  18. }
  19. }(function () {
  20. function extend () {
  21. var i = 0;
  22. var result = {};
  23. for (; i < arguments.length; i++) {
  24. var attributes = arguments[ i ];
  25. for (var key in attributes) {
  26. result[key] = attributes[key];
  27. }
  28. }
  29. return result;
  30. }
  31.  
  32. function decode (s) {
  33. return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
  34. }
  35.  
  36. function init (converter) {
  37. function api() {}
  38.  
  39. function set (key, value, attributes) {
  40. if (typeof document === 'undefined') {
  41. return;
  42. }
  43.  
  44. attributes = extend({
  45. path: '/'
  46. }, api.defaults, attributes);
  47.  
  48. if (typeof attributes.expires === 'number') {
  49. attributes.expires = new Date(new Date() * 1 + attributes.expires * 864e+5);
  50. }
  51.  
  52. // We're using "expires" because "max-age" is not supported by IE
  53. attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';
  54.  
  55. try {
  56. var result = JSON.stringify(value);
  57. if (/^[\{\[]/.test(result)) {
  58. value = result;
  59. }
  60. } catch (e) {}
  61.  
  62. value = converter.write ?
  63. converter.write(value, key) :
  64. encodeURIComponent(String(value))
  65. .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
  66.  
  67. key = encodeURIComponent(String(key))
  68. .replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
  69. .replace(/[\(\)]/g, escape);
  70.  
  71. var stringifiedAttributes = '';
  72. for (var attributeName in attributes) {
  73. if (!attributes[attributeName]) {
  74. continue;
  75. }
  76. stringifiedAttributes += '; ' + attributeName;
  77. if (attributes[attributeName] === true) {
  78. continue;
  79. }
  80.  
  81. // Considers RFC 6265 section 5.2:
  82. // ...
  83. // 3. If the remaining unparsed-attributes contains a %x3B (";")
  84. // character:
  85. // Consume the characters of the unparsed-attributes up to,
  86. // not including, the first %x3B (";") character.
  87. // ...
  88. stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
  89. }
  90.  
  91. return (document.cookie = key + '=' + value + stringifiedAttributes);
  92. }
  93.  
  94. function get (key, json) {
  95. if (typeof document === 'undefined') {
  96. return;
  97. }
  98.  
  99. var jar = {};
  100. // To prevent the for loop in the first place assign an empty array
  101. // in case there are no cookies at all.
  102. var cookies = document.cookie ? document.cookie.split('; ') : [];
  103. var i = 0;
  104.  
  105. for (; i < cookies.length; i++) {
  106. var parts = cookies[i].split('=');
  107. var cookie = parts.slice(1).join('=');
  108.  
  109. if (!json && cookie.charAt(0) === '"') {
  110. cookie = cookie.slice(1, -1);
  111. }
  112.  
  113. try {
  114. var name = decode(parts[0]);
  115. cookie = (converter.read || converter)(cookie, name) ||
  116. decode(cookie);
  117.  
  118. if (json) {
  119. try {
  120. cookie = JSON.parse(cookie);
  121. } catch (e) {}
  122. }
  123.  
  124. jar[name] = cookie;
  125.  
  126. if (key === name) {
  127. break;
  128. }
  129. } catch (e) {}
  130. }
  131.  
  132. return key ? jar[key] : jar;
  133. }
  134.  
  135. api.set = set;
  136. api.get = function (key) {
  137. return get(key, false /* read as raw */);
  138. };
  139. api.getJSON = function (key) {
  140. return get(key, true /* read as json */);
  141. };
  142. api.remove = function (key, attributes) {
  143. set(key, '', extend(attributes, {
  144. expires: -1
  145. }));
  146. };
  147.  
  148. api.defaults = {};
  149.  
  150. api.withConverter = init;
  151.  
  152. return api;
  153. }
  154.  
  155. return init(function () {});
  156. }));

2.使用

1.存到Cookie去

  1. // Create a cookie, valid across the entire site:
  2. Cookies.set('name', 'value');
  3.  
  4. // Create a cookie that expires 7 days from now, valid across the entire site:
  5. Cookies.set('name', 'value', { expires: 7 });
  6.  
  7. // Create an expiring cookie, valid to the path of the current page:
  8. Cookies.set('name', 'value', { expires: 7, path: '' });

2.在Cookie中取出

  1. // Read cookie:
  2. Cookies.get('name'); // => 'value'
  3. Cookies.get('nothing'); // => undefined
  4.  
  5. // Read all visible cookies:
  6. Cookies.get(); // => { name: 'value' }

3.删除

  1. // Delete cookie:
  2. Cookies.remove('name');
  3.  
  4. // Delete a cookie valid to the path of the current page:
  5. Cookies.set('name', 'value', { path: '' });
  6. Cookies.remove('name'); // fail!
  7. Cookies.remove('name', { path: '' }); // removed!

.

cookie 封装的更多相关文章

  1. cookie封装函数(添加,获取,删除)

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>& ...

  2. cookie封装函数与使用方法(转)

    函数封装: var Cookie = function(name, value, options) { // 如果第二个参数存在 if (typeof value != 'undefined') { ...

  3. JS-记住用户名【cookie封装引申】

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  4. cookie封装

    //设置cookie function setCookie(name,value,days){     //如果不设置天数 , 默认为30天     days=days?days:30;     va ...

  5. 2-9 js基础 cookie封装

    // JavaScript Document 'use strict'; function setCookie(sName,sValue,iDay){ if(iDay){ var oDate = ne ...

  6. cookie 和 session 基本使用 以及 封装

    Cookie: 是一小段文本信息,用户请求页面的时候,在浏览器和服务器之间传递.用户每次访问的时候都会记录cookie,cookie里可以包含用户信息,浏览的历史记录等等:Cookie是由服务器端生成 ...

  7. 简单的cookie读写封装

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. cookie方法封装

    将cookie封装主要是为了方便使用,可通过修改参数直接引用在其他需要的地方,不用重新写. 1.添加,删除,修改cookie /** * @param name name:cookie的name * ...

  9. [JavaEE笔记]Cookie

    引言 由于 Http 是一种无状态的协议,服务器单从网络连接上无从知道客户身份. 会话跟踪是 Web 程序中常用的技术,用来跟踪用户的整个会话.常用会话跟踪技术是 Cookie 与 Session. ...

随机推荐

  1. [CODE FESTIVAL 2016]Problem on Tree

    题意:给一棵树,对于一个满足以下要求的序列$v_{1\cdots m}$,求最大的$m$ 对$\forall1\leq i\lt m$,路径$(v_i,v_{i+1})$不包含$v$中除了$v_i,v ...

  2. ReactNative 调用手机地图(高德、百度)导航 Android

    由于项目需要,鉴于第三方sdk包的体积略大,经过评估论证后,决定采用调起APP以及网页地图的方式来进行导航. 思路: 在需要调用导航的界面通过原生获取当前手机内可用的导航app组装成列表返回到RN待选 ...

  3. Android的Master/Detail风格界面中实现自定义ListView的单选

    原文在这里:http://duduli.iteye.com/blog/1453576 可以实现多选,那么如何实现单选呢,这里我写了一个非常简单的方法: public void onListItemCl ...

  4. linux里install命令和cp命令的区别

    转:http://blog.yikuyiku.com/?p=2659 基本上,在Makefile里会用到install,其他地方会用cp命令. 它们完成同样的任务——拷贝文件,它们之间的区别主要如下: ...

  5. 解析天气预报JSON数据

    解析天气预报JSON数据 JSON字符串 constjson2 = '{' + #13#10 +'"error":0,' + #13#10 +'"status" ...

  6. 如何将Emmet(ZenCoding)安装到到Dreamweaver8?

    用过其他版本的Dreamweaver,还是习惯了Dreamweaver8,占用少,插件也容易安装,下面讲的是ZenCoding插件的安装方法,当然现在这个已经叫Emmet了. 安装方法: a.下载dw ...

  7. Android RecyclerView (一) 使用完全解析

    转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/45059587: 本文出自:[张鸿洋的博客] 概述 RecyclerView出现 ...

  8. 安卓源码下载 windows

    git clone https://android.googlesource.com/name Name Descriptionaccessories/manifest device/asus/deb ...

  9. 《CUDA并行程序设计:GPU编程指南》

    <CUDA并行程序设计:GPU编程指南> 基本信息 原书名:CUDA Programming:A Developer’s Guide to Parallel Computing with ...

  10. STL源码剖析——hashtable

    二叉搜索树具有对数时间的搜索复杂度,但是这样的复杂度是再输入数据有足够的随机性的假设上哈希表在插入删除搜索操作上也具有常数时间的表现,而且这种表现是以统计为基础,不需要依赖输入元素的随机性 hasht ...