js 获取和设置cookie

function setCookie(cname, cvalue, exSeconds = 30) {  //默认30分钟
  var d = new Date();
  d.setTime(d.getTime() + (exSeconds*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
} 

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) === ' ') {
          c = c.substring(1);
       }
       if (c.indexOf(name) === 0) {
          return c.substring(name.length, c.length);
       }
   }
  return null;
} 

  

posted @ 2021-11-09 15:37  狂奔的老鳖  阅读(330)  评论(0编辑  收藏  举报