+ Start a Discussion

Ho to access Cookies from different visualforce pages



Can a cookie be set from a vf page other than the page where I actually want to access it? I have two visual force pages. PageA and PageB.


Where PageA is the home page and PageB is where I am actually computing some value and want to set that value as cookie on Page A.


I could set the cookie and read it from PageB but when I am trying to read the same cookie from pageA, ot shows null value. 

Here is the code snippet of what I am trying to do...

In pageB:


//Setting the cookie



 Cookie ck =  new Cookie('newcounter',newcounterval,null,360,false);
        List<Cookie> ls = new List<cookie>();
        pagereference pg = new pagereference('/apex/managecampstest');


 Cookie ck =  new Cookie('newcounter',newcounterval,null,360,false);

  List<Cookie> ls = new List<cookie>(); 



  pagereference pg = new pagereference('/apex/PageA'); 



//Reading the cookie from PageB:



Cookie cook = pg.getCookies().get('newcounter');

        System.debug('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ cookie value'+ cook);  //displays the correct cookie value



In page A


 Cookie counter = ApexPages.currentPage().getCookies().get('newcounter');
    cookievalue = String.valueOf(counter.getValue());//displays null here


Tried this as well:


 pagereference pg = new pagereference('/apex/PageA');
    Cookie cook = pg.getCookies().get('newcounter');
        System.debug('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ cookie value'+ cook); // displays null here as well


Any help is greatly appreciated.




skimmed, but


as long as both pages are in the same force.com site, that is possible (and is the entire point of the cookie functionality).




  • Your code creates a pagereference from a relative path.  you can't do this (well) in sites.  use Page.PageName instead
  • Cookies only work in Sites, so debugging them with the /apex/pagename path in the development context isn't going to work.