cookie属性max-age与expires

max-age表示最大生命周期,expires表示过期时间,cookie使用其中任何一个,都可以用来限制cookie的生效时间。

如果同时使用,max-age会生效。

这两者在时间设置上,却有不同单位属性。expires使用的是当前时间的毫秒+过期的毫秒,因此单位以ms计,而max-age直接使用秒为单位。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>cookie</title>
    <style>
        #root input{padding:10px;border:1px solid #ddd;color:#fff;border-radius: 3px;background: lightgreen;font-size: 16px;}
        #root .box{padding:5px;}
        #root textarea{width:790px;height:200px;resize: none;}
    </style>
</head>
<body>
    <div id="root">
        <div class="box">
            <input type="button" value="expires" onclick="handlecookie(1)"/>
            <input type="button" value="max-age" onclick="handlecookie(2)"/>
            <input type="button" value="expires max-age" onclick="handlecookie(3)"/>
        </div>
        <div class="box">
            <textarea id="output"></textarea>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-1.12.4.js" ></script>
    <script>
        function setCookie(name,value,expires,maxAge){
          var now = new Date()
          now.setTime(now.getTime()+expires)
          var cookiestr = name+"="+value
          if(expires)
            cookiestr+="; expires="+now.toGMTString()
          if(maxAge)
            cookiestr+="; max-age="+maxAge
          document.cookie = cookiestr;
        }
  
        var count = 1;
        var timeout;
        function getCookie(name){
          var cookiestr = document.cookie+"#"+(count++);
          var val = $("#output").val()
          val += cookiestr+"\n"
  
          if(document.cookie){
            $("#output").val(val)
            timeout = setTimeout(function(){
              getCookie(name)
            },1000)
          }else{
            clearTimeout(timeout)
          }
  
        }
  
        function handlecookie(type){
          var expires = 5*1000;
          var maxAge = 10;
          count = 1
          clearTimeout(timeout)
          if(type==1){
            setCookie("age","18",expires)
          }else if(type==2){
            setCookie("age","18",0,maxAge)
          }else{
            setCookie("age","18",expires,maxAge)
          }
          getCookie("age")
        }
    </script>
</body>
</html>

  

页面上有三个按钮,依次点击,看效果:过期时间设置的是5秒,最大生命周期设置的是10秒,单独设置,各自生效,一起设置max-age生效。

    第一个按钮:

   第二个按钮:

  第三个按钮:

 

 

posted @   北京流浪儿  阅读(2170)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示