document.cookie =“cookiename = cookievalue; 期满=星期一,12Jun2015:00:00:00;路径= /;“
我在我的Internet Explorer 10上运行此脚本,但它不在2 IE标签之间共享cookie。但当我删除“过期”属性,所以它似乎工作:
document.cookie= "cookiename=cookievalue ;path=/;"
但我不想删除“过期”属性。那么如何解决这个问题呢?
答案 0 :(得分:20)
我从90年代中期开始使用此代码 - 到目前为止,它已在所有平台上的所有浏览器中使用
包含文件并使用
setCookie("name","value",expiryDate,"/");
// cookie.js file
var cookieToday = new Date();
var expiryDate = new Date(cookieToday.getTime() + (365 * 86400000)); // a year
/* Cookie functions originally by Bill Dortsch */
function setCookie (name,value,expires,path,theDomain,secure) {
value = escape(value);
var theCookie = name + "=" + value +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((theDomain) ? "; domain=" + theDomain : "") +
((secure) ? "; secure" : "");
document.cookie = theCookie;
}
function getCookie(Name) {
var search = Name + "="
if (document.cookie.length > 0) { // if there are any cookies
var offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
var end = document.cookie.indexOf(";", offset)
// set index of end of cookie value
if (end == -1) end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
}
}
function delCookie(name,path,domain) {
if (getCookie(name)) document.cookie = name + "=" +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
";expires=Thu, 01-Jan-70 00:00:01 GMT";
}
答案 1 :(得分:0)
以下示例代码将演示如何直接设置您选择的cookie,而无需用户输入。要从您的网站存储Cookie,只需在HTML页面中调用javascript函数,如下所示:
<script type="text/javascript">cookieSet();</script>
真正的工作是通过cookieSet()javascript函数完成的,该函数可以位于HTML页面区域,也可以位于单独的javascript文件中:
var cookieText = "Put your desired cookie value here";
var cookiePrefix = "";
var myPage = location.href;
var wwwFlag = myPage.indexOf('www');
if (wwwFlag > 0) {
cookiePrefix = "www";
}
var cookieName = cookiePrefix + "cbCookie";
function cookieSet() {
if (document.cookie != document.cookie) {
index = document.cookie.indexOf(cookieName);
} else {
index = -1;
}
if (index == -1) {
document.cookie=cookieName+"="+cookieText+"cbEndCookie; expires=Monday, 04-Apr-2020 05:00:00 GMT";
}
}