html页面怎么保存和读取cookie 推荐MDN封装的cookie方法

做开发时会时不时的用到cookie来保存数据,比如常见的登录页面的username和password,那么html页面中怎么去操作cookie呢?

设置与获取cookie

其实最简单的对cookie的操作就是document.cookie='username=TestUser'(设置cookie),取值时用document.cookie(获取cookie)就可以了

<button onclick="document.cookie='username=kkkkk'">创建cookie1</button>
<button onclick="document.cookie='age=12'">创建cookie2</button>
<button onclick="alert(document.cookie)">显示cookie</button>

创建和获取cookie

设置cookie时的参数

- cookie的name和value,实际上就是一个字符串,例如:username='kk'
- ;path:可以获取到此cookie的路径,例如:"/"、"/dir"
- ;domain:域名 默认为当前文档位置的路径的域名部分。例如:"test.com"、"blog.csdn.net"
- ; expires:cookie的过期时间,如果不定义则cookie在会话结束(关闭网页)时失效,需要GMT格式,可以使用toGMTString()函数来做格式化,例如:new Date().toGMTString();
- ;secure :cookie是否只通过https协议传输

注意

这里有一点需要注意的是,在测试的时候发现谷歌浏览器、新版的Microsoft Edge、QQ浏览器,在打开本地html文件的时候无法获取cookie,能不能储存我没有去深究,但不能获取就是有问题了,上网找了一下,好像是需要部署到服务器或者使用开发工具打开,让它具有一个服务器环境才行,Firefox可以直接使用,上述代码就是在Firefox中测试的。

修改cookie

修改cookie其实只要重新赋值就可以,或者说重新创建名字相同的cookie就好。

<button onclick="document.cookie='username=kk'">创建cookie1</button>
<button onclick="document.cookie='username=xx'">修改cookie1</button>
<button onclick="alert(document.cookie)">显示cookie</button>

修改cookie如上所示,在点击修改一次后,再次点击“创建cookie1”时,cookie的值就被再次修改,所以,cookie的创建和修改的方式是相同的。

删除cookie

上面说过cookie是有过期时间的,如果不设置过期时间,则cookie会在会话结束时自动删除,所以同时也说明没有真的永久的cookie,只有相对永久,比如我们把过期时间设置为9999年1月1日,那么相对来说,这就是一个永久的cookie;
删除cookie,只要把cookie的过期时间修改为已经过去的时间,让cookie失效,那么就是删除了cookie;修改上面已经说过,其实就是从新给cookie赋值,那么删除其实也就是同样的道理了,重新赋值并把失效时间设置为已经过去的时间就是删除cookie

<button onclick="document.cookie='username=kk'">创建cookie</button>
<!-- 现在是:2020年2月18日14:15:17 -->
<button onclick="document.cookie='username=kk;expires=Fri, 31 Dec 2019 23:59:59 GMT'">删除cookie</button>
<button onclick="alert(document.cookie)">显示cookie</button>

删除cookie

获取指定的cookie值

在第一个GIF中我们可以看到,当cookie有多个值得时候,获取到的值是用";"连接每个cookie值的字符串,所以,我们完全可以使用var cookieArr = document.cookie.split("; ")来分割获取到的字符串获得字符串数组,然后遍历数组,来得到指定的值;
或者用网上更多的经过简单封装的正则的方式

function getCookie(name){
 var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)){
        return (arr[2]);
    }else{
         return null;
    }      
}

Cookie封装

不过,在写这篇文章时,在MDN的技术文档中找到了一个经过封装的cookie方法,可以拿过来直接用,各个参数的解释也都有,不需要自己去摸索了。

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  https://developer.mozilla.org/en-US/docs/DOM/document.cookie
|*|
|*|  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) {
    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;
          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 (!sKey || !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) {
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[-.+*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

方法及参数解释:
在这里插入图片描述

  • 8
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值