I want to get community base url in my lightning component without apex. Right now I am using the design component to store the value but that is not optimal as I have multiple page references and typing each of them in the community builder is really hard and error prone.

up vote 5 down vote accepted

Yes, you can retrieve the current page url in your JavaScript controller. And set the value of attribute in your component for later use according to your requirement.

Component

 <aura:attribute name="cbaseURL" type="String"/>

JS Controller

 var urlString = window.location.href;
 var baseURL = urlString.substring(0, urlString.indexOf("/s"));
 component.set("v.cbaseURL", baseURL);

Hope this helps.

EDIT:

As RedDevil highlighted that using window.location can create issues with Microsoft browsers. I tend to search a bit and find out interesting result. So I'd like to all the readers must go through this stackoverflow link to read about the details and use whatever suits you best.

However the widely accepted answer says:

document.location is a synonym for window.location that has been deprecated for almost as long as JavaScript has existed. Don't use it.

location is a structured object, with properties corresponding to the parts of the URL. location.href is the whole URL in a single string. Assigning a string to either is defined to cause the same kind of navigation, so take your pick.

I consider writing to location.href = something to be marginally better as it's slightly more explicit about what it's doing. You generally want to avoid just location = something as it looks misleadingly like a variable assignment. window.location = something is fine though.

  • 1
    use document.location instead of window.location since this has issues in Microsoft browsers. – RedDevil Nov 14 at 16:45

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.