Tips for guaranteeing that the value is retained in an array when setting a Cookie in AEM/cq5

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 "";
    }      
}); });

Answer №1

I highly recommend using the js-cookie library for managing cookies due to its lightweight nature and user-friendly features. You can find more information about it here.

If you are working with Pure jQuery and need to handle cookies, you can utilize js-cookie or a jQuery cookie plugin. For the purpose of this explanation, I will focus on using js-cookie.

To integrate js-cookie into your client library, follow these steps:

Take note that the code snippet provided below is tailored to meet specific requirements. Adjustments may be necessary for removing duplicates or dealing with other code dependencies.

var HISTORY = 'urlHistory';
$(function() {
  var currentPage = $("#currentPagePath").val();
  var urls = Cookies.getJSON(HISTORY);
  console.log('before: ', urls);
  if (!urls && currentPage) {
    Cookies.set(HISTORY, [currentPage]);
  } else if ($.isArray(urls)) {
    var full = urls.length >= 3;
    if (full) {
      urls.pop();
    }
    urls.unshift(currentPage);
    Cookies.set(HISTORY, urls);
  }
  console.log('after: ', urls);
});

For testing purposes, you can check out this demo on https://jsfiddle.net/.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating an array of structures through the dynamic addition of struct elements

I have been wrestling with C pointers for hours without success. My goal is to develop a C program that handles flight information, which includes: flight-number, from, to, date, price OS772,Vienna,New York,15.12.2018,638.00 To achieve this, I am readin ...

The Node.js server is failing to retrieve information from the AngularJS application

Having trouble reading data sent from an AngularJS client to the server via $http.post. Can't seem to figure out where I've made a mistake. var data = $.param({ id:$scope.user_id, }); alert(JSON.stringify(data)); $http.post('/getd ...

Troubleshooting issue with AngularJS ng-repeat not functioning properly when using Object key value filter with ng-model

Is there a way to have an object with an ID as a key value pair? For example: friends = { 1:{name:'John', age:25, gender:'boy'}, 2:{name:'Jessie', age:30, gender:'girl'}, 3:{name:'Johanna', ag ...

Sorting an array of Material-UI's <TableRow> alphabetically using ReactJS and Material-UI. How to do it!

I am currently utilizing Material-UI's <Table> and <TableRow> components by rendering an array of <TableRow>s using the .map() method. Each <TableRow> contains a <TableRowColumn> representing a first name, for example: &l ...

Enhancing Bootstrap modals with dynamic content and integrating Ajax for dynamic data retrieval in Laravel

I am facing some challenges while coding in Laravel, specifically with passing data to a modal (using the Bootstrap framework) and sending data to an Ajax post request. I have an array of items with an 'id', a 'name', and 'content& ...

Content changing programmatically does not reset the scrollHeight

As I embark on the journey to expand my coding skills, I have decided to challenge myself by tackling some tasks without relying on jQuery. One particular challenge that I am currently facing involves a fixed contenteditable div. The goal is to adjust the ...

How can I pass a value from a jQuery variable to a PHP variable?

Utilizing jQuery to create a table based on the output of JSON. The JSON values are retrieved from a SoapClient, which is functioning correctly and producing the desired output. https://i.sstatic.net/vJbfW.png Now, the goal is to assign the value of the ...

What are the steps to transition from @zeit/next-sass deprecation?

Is there a way to transition and modify the next.config.js file to switch from using @zeit/next-sass to leveraging Next.js's built-in support for Sass? Check out this link for more information: https://www.npmjs.com/package/@zeit/next-sass const withS ...

Why am I receiving the error message "Argument of type 'number' is not assignable to parameter of type 'never'?"

import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { showSecret = false; logArr ...

Wicked PDF - Pausing to Allow AJAX Request Completion

My challenge lies in creating a PDF using WickedPDF, where all my static HTML/CSS content loads perfectly. However, I am facing an issue with certain elements on the page which are populated through AJAX requests—they do not appear in the generated PDF. ...

Is there a way in jQuery Validation to apply a rule to the entire form rather than just individual elements within the form?

I am facing an issue with a form where each element has its own custom rules that work perfectly. However, the form cannot be submitted unless values are provided for at least one of its elements. It seems like this is a rule for the entire form rather th ...

Utilizing Redux Reselect for Comment Filtering

Currently, I am attempting to filter and showcase comments that have a matching 'postID' with the current post id. Utilizing Redux/Reselect, the functionality works well but occasionally an error pops up indicating that post._id is undefined/null ...

Encountering an Express.js HTTP 500 ERROR when using res.send("Some text"); is working on the page, however, the error occurs when trying to use res.render('file');

My website has a page located at /request that features a form. The form's method is POST and the action leads to /request. In the POST handler in request.js, the intention is to take action with the form data, like storing it in a database, and then ...

Changes to attributes of an HTML tag cannot be made by jQuery code during an AJAX call

Could someone help me figure out why this jQuery code is not functioning properly? I have already tested it outside the $(document).ready block with no success. Note: The unusual "{{ }}" and "{% %}" syntax is typically used in Django. jQuery $(document) ...

Accessing JSON data from an external source using PHP

I need assistance with reading JSON data from PHP. Here is a snippet of the JSON I am working with: [{ "titulo": "DontAsk", "pais": "Austria", "country_iso": "AT", "direccion": "Mag. Th. Langmann Gmbh Landstrasse 4", "cp_ciudad": "A-2000 STO ...

Is there a way to eliminate the border of an image attribute pulled from an input field?

Seeking assistance with a persistent issue I'm facing. I have an input for an image and a script to display the selected image. However, when the input is empty, a frustrating black border appears around the image attribute. How can I remove this bord ...

Utilizing Conditional Logic to Create a Dynamic Menu

I have a navigation menu on my website that is divided into two sections. There is a left panel and a right panel which slide in from the side when their respective buttons are clicked, covering the browser window. The functionality of sliding in the pan ...

Vue-router and middleman combination displaying '404 Error' upon page refresh

I'm in the process of developing a website that utilizes Middleman (Ruby) on the backend and VueJS on the front end, with vue-router managing routing. Specifically, in my vue-router configuration, I am rendering the Video component on /chapter/:id as ...

Asynchronously loading images within a div that has overflow: scroll, as they come into view

The setup I have for displaying my content looks like this: <div id="content" style="overflow:scroll;height:500px; width: 500px;"> <div style="width:500px;height:100px;> <img src='http://graph.facebook.com/user1/picture?width= ...

Having trouble with jQuery validation: Seeking clarification on the error

I have implemented some validations on a basic login page and added jQuery validation upon button click. However, the code is not functioning as expected. I have checked the console for errors but none were displayed. Here is the code for your review: ...