javascript设置cookie高级篇可跨域访问

2023-05-11 16:09:42 浏览数 (2)

推荐使用:

代码语言:javascript复制
//根据名称获取Cookie
function getCookie(cname) {
    var name = cname   "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i  ) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return null;
};

//设置Cookie; 参数cname名称,cvalue值,exdays天数
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime()   (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires="   d.toGMTString();
    document.cookie = cname   "="   cvalue   "; "   expires   ";path=/;domain=.xxxxx.com";
};
//使用时一定要修改 .xxxxx.com 为你的域名,  如www.baidu.com 改为.baidu.com

常规操作

参考:JavaScript Cookie | 菜鸟教程

代码语言:javascript复制
function setCookie(cname,cvalue,exdays){
    var d = new Date();
    d.setTime(d.getTime() (exdays*24*60*60*1000));
    var expires = "expires=" d.toGMTString();
    document.cookie = cname "=" cvalue "; " expires;
}
function getCookie(cname){
    var name = cname   "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i  ) {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
    }
    return "";
}
function checkCookie(){
    var user=getCookie("username");
    if (user!=""){
        alert("欢迎 "   user   " 再次访问");
    }
    else {
        user = prompt("请输入你的名字:","");
          if (user!="" && user!=null){
            setCookie("username",user,30);
        }
    }
}

跨域访问cookie (仅支持二级域名) 参考:javascript跨域设置cookie(二级域名)_xuebingnan的博客-CSDN博客

代码语言:javascript复制
function setCookie(c_name, value, expiredays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate()   expiredays);
        document.cookie = c_name   "="   escape(value)   ((expiredays == null) ? "" : ";expires="   exdate.toGMTString()   ";path=/;domain=.testdomain.com")
    }

    var AdTime = new Date(); 
    if (AdTime != "") {

        setCookie("AdTime", AdTime, 1);
    }

0 人点赞