It isn't entirely obvious how a developer can determine the hostname (server url) portion of the absolute path for a Visualforce page via Apex. Luckily, it is rather easy to do.
You might have already figured out that the PageReference class's getUrl() method will return the relative path for your Visualforce page:
ApexPages.currentPage().getUrl();
Once you have the relative path for the page, then there's just one remaining trick to discover - the Map returned by the PageReference class's getHeaders() method contains a 'Host' key whose associated value is the hostname for your salesforce org:
ApexPages.currentPage().getHeaders().get('Host');
The complete code for constructing the absolute path for a Visualforce page is below:
String hostname = ApexPages.currentPage().getHeaders().get('Host');
String pageUrl = ApexPages.currentPage().getUrl();
String absolutePath = 'https://' + hostname + pageUrl;
system.debug(absolutePath); //example output: 'https://na6.salesforce.com/apex/MyPage'
Wednesday, October 08, 2008
Visualforce Tip: How to Determine a salesforce.com Hostname
Labels: Apex, Visualforce
Subscribe to:
Post Comments (Atom)
3 comments:
Nice solution. Any idea how to get the url using Apex? The only thing I can think of is looking at the org id and see if it is our production org id.
Jeff - Determining the host from within Apex, but outside of the context of Visualforce is a bit harder. Here are some work-arounds:
http://ideas.salesforce.com/article/show/10091004/Apex_method_to_identify_salesforcecom_server
http://community.salesforce.com/sforce/board/message?board.id=Visualforce&thread.id=7697&view=by_date_ascending&page=1
I tried this. The issue is that the URL generated is of Visualforce like
Contact Link: https://tr1.na12.visual.force.com/003U000000S9qXvIAJ
Is there a way to get the URL like https://na12.salesforce.com? Without parsing it?
Post a Comment