Home >Web Front-end >JS Tutorial >How to set, get and delete cookies in javascript_javascript skills
The example in this article describes the method of setting, obtaining and deleting cookies in javascript. Share it with everyone for your reference. The specific implementation method is as follows:
/* *设置Cookie * * name:cookie所对应的键 * value:cookie所对应的值 * expires:cookie所对应的有效时间 * path:指定可访问cookie的路径 * domain:指定可访问cookie的主机名 * secure:安全性 */ function setCookie (name,value,expires,path,domain,secure) { //cookie键值对 var str = name + "=" + escape(value); //设置cookie的有效期,以小时为单位 if(expires > 0){ var date = new Date(); var ms = expires * 3600 * 1000; date.setTime(date.getTime() + ms); str += "; expires=" + date.toGMTString(); } if(path){ str += "; path=" + path; } if(domain){ str += "; domain=" + domain; } if(secure){ str += "; secure"; } document.cookie = str; } /* *获得Cookie * *cookie_name:cookie的键 */ function getCookie(cookie_name) { var value = null; var allcookies = document.cookie; var cookie_pos = allcookies.indexOf(cookie_name); // 如果找到了索引,就代表cookie存在, // 反之,就说明不存在。 if (cookie_pos != -1) { // 把cookie_pos放在值的开始,只要给值加1即可。 cookie_pos += cookie_name.length + 1; var cookie_end = allcookies.indexOf(";", cookie_pos); if (cookie_end == -1) { cookie_end = allcookies.length; } value = unescape(allcookies.substring(cookie_pos, cookie_end)); } return value; } /* *删除Cookie * *cookie_name:cookie的键 */ function delCookie(cookie_name) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var value = getCookie(cookie_name); if(value){ document.cookie= cookie_name + "=" + value + ";expires=" + exp.toGMTString(); } }
I hope this article will be helpful to everyone’s JavaScript programming design.