How to read cookies set by JavaScript in a Salesforce Apex Class

How to read cookies set by JavaScript in a Salesforce Apex Class
Sharing is Caring

I recently had a requirement to have JavaScript create a cookie and then read it in later by an Apex class. You would think you could simply create a cookie in JavaScript and then read it in Apex using the exact same name as the cookie, but that’s not exactly the case.

Cookies that need to be read by an Apex Class need to start with apex__ or they won’t be readable by Apex. One other thing to keep in mind is that if apex changes the cookies values they will be url encoded. For example, the @ symbol will have it’s value changed to the percentage sign and the hexadecimal version.

For this example, we’re assuming you want to set a cookie called “settings” to true as soon as the javascript loads. I’m using a standard pattern I’ve documented previously about using jQuery in Visualforce.


<script>

function j$(function() {
setCookie('apex__settings','true');
});

function setCookie(cookieName, value){
    var cookieString = cookieName + "=" + value;
    document.cookie = cookieString;
}
</script>


To access the values in apex, we would probably have some sort of functions like the below examples.


 	private string savedSettings = null;
 
 	public PageReference OnLoad()
 	{
 		savedSettings = getCookie('settings');
 	}

// Private method used to set the cookie value
	private void setCookieString(String cookieName, String value)
   	{
		Cookie ck = ApexPages.currentPage().getCookies().get(cookieName);
		
		ck = new Cookie(cookieName, String.valueOf(value),null,-1,false);
		
		ApexPages.currentPage().setCookies(new Cookie[]{ck});
	}
	
	// Private method used to retrieve the cookie value
	private String getCookie(String cookieName)
	{
		Cookie ck = ApexPages.currentPage().getCookies().get(cookieName);
 		
	    return ck != null ? ck.getValue() : '';
	}   

Author: Brian Cline

Brian is a programmer living in Niagara Falls with ten years of development experience. He is passionate about automation, business process re-engineering, and gamification. For the last six years or so, he has been working with Salesforce and JavaScript.

Related Posts

Sharing is Caring