Monday 24 June 2013

Page Views Counter widget in salesforce

Hi All,
Today, I am going to show you an application of cookies in context of salesforce. I think, at many discussion boards and blog areas you have seen number of page views or visitor counter on top of that if not you can see it on this current blog in right panel. So what I implemented is same counter widget in salesforce using cookies. Cookies is a API which helps you to let your browser remember many things which you don't want. So here I have composed it with in VF page, Apex class & to expose it I have used force.con site feature.




Please Click on below link to get Demo.
Demo Link

 Visualforce Page:

  
      
          You are visitor number : {!visitorNumber}
      
  

Apex Class:
public class PageviewCouterUtilClass {
    public String visitorNumber{get;private set;}
    public PageviewCouterUtilClass () {
        Cookie PageCounter = ApexPages.currentPage().getCookies().get('PageCounterCookie');
         
        // User is accessing page first time       
        if (PageCounter == null) {
            PageCounter = new Cookie('PageCounterCookie','1',null,-1,false);// create a new cookie 'PageCounterCookie', an initial value : '1', path :  'null', maxAge  : '-1'and isSecure : 'false'.
        } else {        
            Integer visitorNumber = Integer.valueOf(PageCounter.getValue());
            PageCounter = new Cookie('PageCounterCookie', String.valueOf(visitorNumber+1),null,-1,false);
        }    
        // Set the new cookie for the page
        ApexPages.currentPage().setCookies(new Cookie[]{PageCounter});  
        if(PageCounter == null) 
        {
            visitorNumber = '0';
        }   
        else
        {
            visitorNumber =  PageCounter.getValue();
        }     
    }
}

Here is a limitation of loosing counter in case of deleting cookies in this case counter will be reset. To avoid this problem you can store this counter value in your salesforce org like custom setting.

Thanks 
Sandeep

No comments:

Post a Comment