To get cookie using JS (Not USE-API)

viki1101

04-09-2020

Hello Community - Could you give some idea about to fetch the cookie in the component using JavaScript/Jquery but not USE-API. and I wanted to pass the cookie value to WCMUsePojo using data-sly-use.

 

<div data-sly-use.userInfo="${'com.xyz.aem.core.models.UserDetails' @ childNode='test', cookieValue={Need to Pass the cookie value}"  data-sly-unwrap>

Accepted Solutions (1)

Accepted Solutions (1)

surabhikatiyar

Employee

06-09-2020

The cookie value cannot be sent through Javascript to the WCMPojo, because the javascript section loads after the HTML/JSP has been loaded. So, even if you fetch the cookie value using Javascript it will never reach the WCMPojo class until you reload via some dynamic template binding.

 

The other options are:-

1. Directly fetch the cookie in WCMPojo class using the request object

 

Cookie[] cookies = request.getCookies();
for (Cookie cookie: cookies) {
    String value = cookie.getValue();
}
 
2. Use the  USE-API
 

-------- script.js -------------

// Server-side JavaScript to get Coookie

use(function () {

var cookie = request.getCookie("wcmmode");

var cookieFound=false;

if(cookie!=null && cookie.value=="edit"){

cookieFound = true;

}

return {

cookieVal: cookie.value,

cookieFound:cookieFound

};

});

-------- Sightly code --------------

<sly data-sly-use.cObj="script.js" data-sly-test="${cObj.cookieFound }">

${cObj.cookieVal}

</sly>

Answers (2)

Answers (2)

Singaiah_Chintalapudi

MVP

05-09-2020

It is much easier to use HTML attributes of this div tag and use JS/jQuery to inject the cookie value into this cookieValue attribute.

 

What's the requirement to fetch this on sightly?

 

Thanks,

Singaiah

Vaibhavi

MVP

04-09-2020

Hi @viki1101 , 

 

You cannot pass the value from client to server side. 

If you need to set any html attribute value through js , yes it is possible using js functions but here you are trying to pass the value set from client to server which not possible. 

You can use any one of the option below to fetch the cookie. 

1.Using USE-API,fetch the value in js using below method 

request.getCookie("cookiename")

2. Instead of passing the cookie from slightly, fetch the cookie directly in wcmpojo class(java) . 

Cookie[] cookies = request.getCookies();
for (Cookie aCookie : cookies) {
    String name = aCookie.getName();
    String value = aCookie.getValue();
}