How do you read cookies set by JavaScript in the Apex/Visualforce controller?
This might be a requirement if you are developing some complex navigation, for example:
The user lands on a Visualforce page: “A”.
From here, the user is redirected to another page: "B”.
Now, when that user returns to page “A” you want to ensure some operations are done on page “B”. Of course, one can create database records for the same. But that might be too much to maintain for some trivial tracking requirements. So Cookies seem to be a good fight in this scenario. If some desired operation is done on page “B”, a cookie can be set, which in turn can be read by Apex Controller on page “A.”
Life is good, if you are setting and retrieving cookies both by Apex code. But but but, if you are using some other mechanism to create cookies, i.e. via Javascript, then we need to do a little “HACK” to make those cookies available to Apex.
WTH—What’s the “HACK”?
Cookies created and read by Apex code are transparently prefixed by “apex__”. If you are creating a cookie called “ShoppingCart” in Apex, it will become a cookie with the name “apex__ShoppingCart” on the client’s machine. So, if one is creating cookies from non-apex code, that is finally meant to be read back by apex code, then just prefix the cookie name with "apex__”.
And if you want to create cookies by Javascript, then simply prefix them with "apex__”. For example, I want a cookie named “external_cookie” available to Apex code, this cookie should be created via Javascript as shown below:
Now in your apex code, you can easily access this cookie with the name “external_cookie”. See the code snippet shown below:
System.Cookie cookie = ApexPages.currentPage().getCookies().get('external_cookie');
References & thoughts!
I would like to express thanks to Mr. Andred Mahood; this interesting point was figured out during my X (formerly Twitter) discussions with him.