[SalesForce] way to detect if a Lightning Component is running in a Community or in Lightning Experience

I have a Lightning Components and need to know if it is running inside of a Community or in Lightning Experience.

Is there a way to detect the running context?

Right now I'm checking document.location against a hardcoded Community-path but I need a general solution.

Best Idea I have so var to make it dynamic is to check for '/s/' in the URL. But I'm not sure if this is reliable for all possible Community pages. Also it feels like an hack.

After detecting the context, I also need to get the URL Prefix from the community. Again I could cut it out of the path, but would prefer otherwise.

Googling around didn't brought much. So far I found some context-aware unanswered questions here:

Best Answer

You can try to use the SessionManagement Class's getCurrentSession() method, which will return a map of attributes for the users current session. Amongs these, you will find SessionType, which will indicate the context. Here are some that I tested:

Lightning Communities:

  • Preview & Builder mode: SitePreview or LivePreview
  • Live Site: ChatterNetworks

Lightning Experience:

  • LEX App page: Aura

further details can be found at Understanding Session Types

You will have to do this in an Apex class and call your method to get the context in your clientside controller.

Related Topic