I'm facing an issue with AEM where the page path needs to be added to a cookie each time a user visits a specific type of page. The requirement is to store a maximum of 3 pages in the recently visited section of the cookie. Initially, I attempted to use request.getCookies(), but encountered a problem where the cookie value was not always fetched correctly. However, after a few page refreshes, it would display correctly.
Another requirement is that the array should be arranged from the most recent (position 0) to the oldest, hence the use of unshift.
As a solution, I started using document.cookie to set up 3 separate cookies to store each page link. However, I faced an issue with the splice function in the provided code. The first item in the array was always being replaced, resulting in the array retaining only 1 value. I'm unsure of why this is happening as the code seems correct:
document.addEventListener("DOMContentLoaded", function(event) {
$(function () {
$(document).ready(function () {
var paths = [];
var cookie0 = getCookie("cookie0");
if (cookie0 != "")
paths.push(cookie0);
var cookie1 = getCookie("cookie1");
if (cookie1 != "")
paths.push(cookie1);
var cookie2 = getCookie("cookie2");
if (cookie2 != "")
paths.push(cookie2);
//syntax for cookie: path1 + separator + path2 + separator + path3
var separator = '&';
var newpath = document.getElementById("currentPagePath").value; //the fund page we're viewing and want to add to the cookie
//first check if the page is under a specific type
if(newpath.indexOf("type") != -1) //if it is under a certain page type, then add to the cookie
{
//check if the newpath exists already in the cookie positions, can only have max 3 but don't want duplicates listed of the same page
var foundPos = paths.indexOf(newpath);
//will need to remove from pos if found or if length is 3
if(foundPos >-1 || paths.length >=3 )
{
paths.splice(foundPos, 1);
}
paths.unshift(newpath);
//finally add to the cookie
setCookie(paths, 30);
}
});
//Set cookie
var setCookie = function (paths, expiryDays) {
for(var i=0;i<paths.length;i++)
{
var expirydate = new Date();
expirydate.setTime(expirydate.getTime() + (expiryDays * 24 * 60 * 60 * 1000));
var expires = "expires=" + expirydate.toGMTString();
document.cookie = "cookie"+i + "=" + paths[i] + ";" + expires + ";path=/";
}
}
//Get cookie
var getCookie = function (cookieName) {
var name = cookieName + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
}); });