I have code which sets Cookie for every folder of domain (for example, domain.com and domain.com/folder, domain.com/folder2) have same Cookie name ("history") and different "history" values. How can i ignore Path for Cookie and add all Cookie value in same name ("history") even if Cookie was set from another folder? I used standart cookie.js (https://github.com/js-cookie/js-cookie) and this additional code:
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 + ';path="/";' + 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 checkHistory(targetId) {
var history = getCookie("history");
var htmlContent = '';
if (history != "") {
var insert = true;
var sp = history.toString().split(",");
for ( var i = sp.length - 1; i >= 0; i--) {
htmlContent += '<div id="recentViewes" data-recentViewes="'
+ sp[i] + '"></div> ';
if (sp[i] == document.URL) {
insert = false;
}
document.getElementById(targetId).innerHTML = htmlContent;
}
if (insert) {
sp.push(document.URL);
}
setCookie("history", sp.toString(), 30);
} else {
var stack = new Array();
stack.push(document.URL);
setCookie("history", stack.toString(), 30);
}
}
答案 0 :(得分:0)
自己找到解决方案:
此代码用于您希望拥有历史记录块的页面:
function checkHistory(targetId) {
var history = getCookie("history");
var htmlContent = '';
if (history != "") {
var insert = true;
var sp = history.toString().split(",");
var se = decodeURIComponent(sp).split(",");
for ( var i = se.length - 1; i >= 0; i--) {
htmlContent += '<div id="recentViewes" data-recentViewes="'
+ se[i] + '"></div> ';
if (se[i] == window.location.pathname) {
insert = false;
}
document.getElementById(targetId).innerHTML = htmlContent;
}
if (insert) {
se.push(window.location.pathname);
}
setCookie("history", se.toString(), 30);
} else {
var stack = new Array();
stack.push(window.location.pathname);
setCookie("history", stack.toString(), 30);
}
}
这适用于域的每个文件夹/页面:
function checkHistory(targetId) {
var history = getCookie("history");
var htmlContent = '';
if (history != "") {
var insert = true;
var sp = history.toString().split(",");
var se = decodeURIComponent(sp).split(",");
for ( var i = se.length - 1; i >= 0; i--) {
htmlContent += '<div id="recentViewes" data-recentViewes="'
+ se[i] + '"></div> ';
if (se[i] == window.location.pathname) {
insert = false;
}
document.getElementById(targetId).innerHTML = htmlContent;
}
if (insert) {
se.push(window.location.pathname);
}
$.cookie('history', se.toString(), { expires: 30, path: '/' });
} else {
var stack = new Array();
stack.push(window.location.pathname);
$.cookie('history', stack.toString(), { expires: 30, path: '/' });
}
}