Does a Lightning Component know if it is in a Community or a standard Lightning Salesforce page?

I have made a blog about how to resolve this issue without having to add a design attribute. Link: http://kevansfdc.blogspot.com/2017/02/does-lightning-component-know-if-it-is.html

The solution I propose is to use a aura enabled method which return whether you are in a site context using the Site class that come natively with Salesforce.

@AuraEnabled
public static boolean isCommunity(){
    Id siteId = Site.getSiteId(); // take a look at the apex class Site, you may find more useful method concerning site/community
    if (siteId != null) {
        return true;
    }
    return false;
}

And simply calling this method through an action in Lightning.

var action = component.get("c.isCommunity");
action.setCallback(this, function(response) {
var isCommunity = response.getReturnValue(); // do any operation needed here
});
$A.enqueueAction(action);

Hope this is useful as an answer. Cheers!


We ended up going for the attribute/property editor route.

Component:

<aura:attribute name="environmentType" type="String" description="This variable is used to indicate which environment this component is displayed on, f.i. community vs standard lightning" />

Design file:

<design:attribute name="environmentType" label="Environment Type" datasource="Community,Standard" required="true" description="Please indicate which environment this component is hosted on."/>

Use the property editor in the Lightning App Builder to set the attribute to the right value for the environment it is on.

Property Editor

Then in your controller/helper you can check which environment the component is viewed on.

var environment = component.get('v.environmentType');
if (environment == 'Community') {
    // Do Community logic
} else if (environment == 'Standard') {
    // Do Standard Lightning logic
}