cookie实例

2016-05-26 09:31:14 作者:瀚海沙 firefox, google, js, cookie

       学习cookie的创建,和检查浏览器是否获取到了cookie,例子就是w3cschool上面的例子,只是在使用过程中发现,firefox获取到了cookie的值,但是,google却没有。于是,查了很多资料,发现很多人碰到了相同的问题,才知道,google在本地页面是不会保存cookie的,于是又添加了一段,显示cookie的值来验证,google是否保存本地页面的cookie这一说法。

<script type="text/javascript">
//设置cookie
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
//获取cookie
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.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) != -1) return c.substring(name.length, c.length);
    }
    return "";
}
function allCookie(){//读取所有保存的cookie字符串 
                var str = document.cookie; 
                if (str == "") { 
                    str = "没有保存任何cookie"; 
                } 
                alert(str); 
            }   
function checkCookie() {
    var user = getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
        user = prompt("Please enter your name:", "");
        if (user != "" && user != null) {
            setCookie("username", user, 365);
        }
    }
}
checkCookie(); 
</script>

<body >
<input type="button" value="读取所有cookie" onclick="allCookie()"/>
</body>

© hanhaisha.com. All Rights Reserved

梦里不知岁月匆、梦醒不知韶华过