Tuesday 31 March 2015

How to Get Current Page URL in Apex

Sometime we need to get current page URL in apex ,Then we need to use Apexpages.currentPage() methods provided by salesforce.
There is following step which you need to follow:
Step 1:
First call 'getHeaders()' method which return a map of the request headers,where the key string contains the name of the header, and the value string contains the value of the header.
After that get the 'Host' key value from that map.
String hostVal  = ApexPages.currentPage().getHeaders().get('Host');
It gives like 'c.ap1.visual.force.com',etc.



Step 2:
Second,you need to call 'getUrl()' method which returns the relative URL associated with the PageReference,including any query string parameters and anchors.
String urlVal = Apexpages.currentPage().getUrl();
It returns as '/apex/pagename','/apex/pageName?check=false' etc.
Step 3: After that add these two values return in step1 and step2 with 'https://'
The whole method is given below:
public void getPageURL() {
    String hostVal  = ApexPages.currentPage().getHeaders().get('Host');
    String urlVal = Apexpages.currentPage().getUrl();
    String URLL = 'https://' + hostVal+ urlVal;
}

6 comments: