设置cookie:
function setCookie(name, value, expTime){ var exp = new Date(); expTime = expTime ? expTime : 365; exp.setTime(exp.getTime() + expTime* 24 * 60 * 60 * 1000); //有效期 document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString(); //cookie名和值 }
获取cookie:
function getCookie(name){ var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (arr != null) return unescape(arr[2]); return null; }
多站点不同域名共享cookie:
比如有a.xxx.com 和 b.xxx.com,可设置在xxx.com,这样a和b两个站点就能共用cookie
function setCookie(name, value, expTime) { var exp = new Date(); expTime = expTime ? expTime : 365; exp.setTime(exp.getTime() + expTime * 24 * 60 * 60 * 1000); document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/;domain=.xxx.com"; }