sessionStorage、localStorage、cookie

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30682027/article/details/83650982

1. cookie

document.cookie

1.1. 会话期Cookie

会话期Cookie是最简单的Cookie:浏览器关闭之后它会被自动删除,也就是说它仅在会话期内有效。会话期Cookie不需要指定过期时间(Expires)或者有效期(Max-Age)。需要注意的是,有些浏览器提供了会话恢复功能,这种情况下即使关闭了浏览器,会话期Cookie也会被保留下来,就好像浏览器从来没有关闭一样

1.2. 持久性Cookie

和关闭浏览器便失效的会话期Cookie不同,持久性Cookie可以指定一个特定的过期时间(Expires)或有效期(Max-Age)。下边是一个http response设置持久cookie的头部内容

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT;

提示:当Cookie的过期时间被设定时,设定的日期和时间只与客户端相关,而不是服务端。

1.3. 写cookie

document.cookie='key=value'

使用document.cookie=,添加或者更新当前cookie,并不是将原来的所有cookie都替换了。

如果没有设置expires或者max-age,那么这个cookie就是会话级cookie(标签或者浏览器关闭时,会被清除.但这并非一定的).否则,就是持久cookie

设置cookie的其它属性:

document.cookie='key=value;expires='+(new Date()).toUTCString()+";path=/;domain=test.com;secure;httponly;"

1.3.1. expires

指定到期时间.UTC时间字符串,如果设置为当前时间,cookie被删除

1.3.2. max-age

指定有效期,单位秒.这是一个用来替代expires的属性.因此作用和expires相同.

1.3.3. path

Path标识指定了主机下的哪些路径可以接受Cookie(该URL路径必须存在于请求URL中)。以字符 %x2F ("/") 作为路径分隔符,子路径也会被匹配。

例如,设置 Path=/docs,则以下地址都会匹配:

/docs
/docs/Web/
/docs/Web/HTTP

但是,设置path并不能有效的阻止cookie被窃取.一种方法是在当前页面嵌入iframe,然后将iframe指向cookie要求的路径,这样就可以实现跨路径获取cookie了

1.3.4. domain

Domain 标识指定了哪些主机可以接受Cookie。如果不指定,默认为当前文档的主机(不包含子域名)。如果指定了Domain,则一般包含子域名。

例如,如果设置 Domain=mozilla.org,则Cookie也包含在子域名中(如developer.mozilla.org)。

1.3.5. secure

标记为secure的cookie,只能用于https.使用时,只用写上secure即可,无需设置值;需要取消时,可重新设置cookie,后边不带secure也就是了.

1.3.6. httponly

不允许javascript获取,只用于http传输.和secure一样,只需要写上httponly标记一下即可.

1.4. 获取cookie

var allCookie = document.cookie;

获取到的allCookie是一个key=value并以分号隔开的字符串.没有expires/path/domain/max-age等说明字段

1.5. 删除cookie

//删除cookie有两种方法

//1. 设置expires为当前时间
document.cookie='key=value;expires='+(new Date()).toUTCString()

//2. 设置max-age为0
document.cookie='key=value;max-age=0'

1.6. MDN操作cookie的示例

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  Revision #3 - July 13th, 2017
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*|  https://developer.mozilla.org/User:fusionchess
|*|  https://github.com/madmurphy/cookies.js
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path[, domain]])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          /*
          Note: Despite officially defined in RFC 6265, the use of `max-age` is not compatible with any
          version of Internet Explorer, Edge and some mobile browsers. Therefore passing a number to
          the end parameter might not work as expected. A possible solution might be to convert the the
          relative time to an absolute time. For instance, replacing the previous line with:
          */
          /*
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; expires=" + (new Date(vEnd * 1e3 + Date.now())).toUTCString();
          */
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

2. Storage

作为 Web Storage API 的接口,Storage 提供了访问特定域名下的会话存储(session storage)或本地存储(local storage)的功能,例如,可以添加、修改或删除存储的数据项。

如果你想要操作一个域名的会话存储(session storage),可以使用 Window.sessionStorage;如果想要操作一个域名的本地存储(local storage),可以使用 Window.localStorage。

sessionStorage instanceof Storage
//true

localStorage instanceof Storage
//true

因为sessionStoragelocalStorage都实现了Storage接口,因此它们都具备Storage的属性和方法

属性:Storage.length 只读
返回一个整数,表示存储在 Storage 对象中的数据项数量。

方法:
Storage.key():该方法接受一个数值 n 作为参数,并返回存储中的第 n 个键名。
Storage.getItem():该方法接受一个键名作为参数,返回键名对应的值。
Storage.setItem():该方法接受一个键名和值作为参数,将会把键值对添加到存储中,如果键名存在,则更新其对应的值。
Storage.removeItem():该方法接受一个键名作为参数,并把该键名从存储中删除。
Storage.clear():调用该方法会清空存储中的所有键名。

2.1. sessionStorage

sessionStorage 属性允许你访问一个 session Storage 对象。它与 localStorage 相似,不同之处在于 localStorage 里面存储的数据没有过期时间设置,而存储在 sessionStorage 里面的数据在页面会话结束时会被清除。页面会话在浏览器打开期间一直保持,并且重新加载或恢复页面仍会保持原来的页面会话。在新标签或窗口打开一个页面时会在顶级浏览上下文中初始化一个新的会话,这点和 session cookies 的运行方式不同

应该注意的是,无论是 localStorage 还是 sessionStorage 中保存的数据都仅限于该页面的协议

2.2. localStorage

只读的localStorage 允许你访问一个Document 的远端(origin)对象 Storage;数据存储为跨浏览器会话。 localStorage 类似于sessionStorage。区别在于,数据存储在 localStorage 是无期限的,而当页面会话结束——也就是说当页面被关闭时,数据存储在sessionStorage 会被清除 。

应注意无论数据存储在 localStorage 还是 sessionStorage ,它们都特定于页面的协议。

猜你喜欢

转载自blog.csdn.net/qq_30682027/article/details/83650982