Thursday, December 3, 2015

How to get salesforce base URL in visual force page at runtime

When we are writing any code related to Salesforce Instance URL it shouldn't be hard coded.The reason behind it when you deeply the the same code to other environments like sandboxes or production the base URL might be changed based on instances.At that point of time your code might breaks and it will stop working.

So whenever your dealing with any URL related stuff it's better to get the instance URL(BaseURL,any other parameters) at run time based on the instance.There are already so many ways that you can get the baseURL in apex but if you want to get it in vf page one way is as below

Getting salesforce instance URL in VF page

   var totalPageURL = window.location.toString();
   var protocalType= totalPageURL.split("//")[0];
   var tempbaseURL = totalPageURL.split("//")[1].split("/");
   var finalBaseURL = protocalType+'//'+tempbaseURL[0];
   alert(finalBaseURL );


Lets take if your page url is like

Then this will give output as (which is baseURL)

To test this snippet on any web page 

1. Just open any web page 
2. Press F12 (for chrome) or Right click open inspect element
3. Click on console 
4. Paste the code by removing <script> tag and press enter

Then you will popup with alert message which displays your BaseURL.

For more info please refer highlighted areas in below image 

Thanks for visiting..Enjoy.....

No comments:

Post a Comment