April 11, 2011

How to read cookies set by JavaScript in Apex/Visualforce controller !

This might be a requirement, if you are developing some complex navigation, for ex.

  • User lands on a visualforce page  “A”
  • from here user is redirected to some other page “B”
  • Now when user returns to page “A” you want to make sure, 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 seems to be a good fight in this scenario, if some desired operation is done on page “B” a cookie can be set, that in turn can be read by Apex Controller at 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 Cookie i.e.  via Javascript, then we need to do a little “HACK” to make those cookies available to apex.

WTH – What 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  be actually a cookie with name “apex__ShoppingCart” created on client’s machine. So, if one is creating cookies from non-apex code, that are finally meant to be read back by apex code, then just prefix the cookie name by “apex__".

So if you want to create cookies by Javascript, then simply prefix them with “apex__”.For ex. I want a cookie named “external_cookie” available to Apex code, this cookie should be created via Javascript as shown below

<apex:page>
  <script>      
      function setCookie(c_name,value,exdays)
        {
        var exdate=new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
        document.cookie=c_name + "=" + c_value;
        }
        setCookie('apex__external_cookie', 'some value set from external cookie', 3);
  </script>
</apex:page>  

Now in your apex code you can easily access this cookie by name “external_cookie” in your apex code, 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 knol was figured out during twitter discussions with him.

image

Looking forward for your thoughts and views on this !