Im trying to access the current logged in user information in a Salesforce Community from pure javascript.

I just have a custom html footer and in the page i was able to do this to to get the name and the email

var loggedInUser = { name: document.getElementsByClassName('globalHeaderProfilePhoto')[0].title, email: UserEmail };

UserEmail seems to be a javascript variable setup by salesforce on the page, and im getting the name from the global header in the dom. Not great but it works..

What Im hoping for is a more reliable way to get the name (not all my user types have to global bar turned on) and a way to get some idea of what the users profile is either the profile ID or Profile name?

Any ideas? I see theres also a UserContext variable but that doesnt seem to have either of those things?

  • Why "from pure javascript"? Where are you using this from? – Adrian Larson Jun 3 '15 at 22:53
  • Its just a static html file set as a footer in the community. There is no way to run visualforce or apex in those pages – Keith Mancuso Jun 3 '15 at 22:54
  • Just checking - Since you are using Javascript, have you tried using Javascript Remoting to pass the userId to a returning method and have it return the User Name and Profile information? – Eric Jun 3 '15 at 22:58
  • @Eric it's a static html file in the footer on a standard page. Sadly JavaScript tempting requires apex and visualforce, right – Keith Mancuso Jun 4 '15 at 1:43
  • @KeithMancuso - Only for the remote action. No controller needed at all just a global remote action class with the proper methods. – Eric Jun 4 '15 at 19:53

Communities Header and Footer customizations like conditional branding, context specific data can be achieved/retrieved using Visualforce injection.
To get the current user related details in json format, you may create a Visualforce page say footer with contentType application/json and call this visualforce page from javascript in Header/Footer html.


<apex:page contentType="application/json">
"username": "{!$User.FirstName} {!$User.LastName}",
"profileName": "{!$Profile.Name}",
"profileId": "{!$User.ProfileId}"

Provide access to this visualforce page for the required user profiles.

Javascript snippet

<script type="text/javascript">
    var xmlhttp = new XMLHttpRequest();
    var url = '/partners/apex/footer';
    xmlhttp.onreadystatechange = function (){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            var jsonObj = JSON.parse(xmlhttp.responseText);
            var username = jsonObj.username;
            var profileId = jsonObj.profileId;
            var profileName = jsonObj.profileName;
    xmlhttp.open("GET", url, true);

url format is /<community url suffix>/apex/<vf page name>. It even works without apex in url like /<community url suffix>/<vf page name>.

Credits to Justin's blog which provided the idea for Visualforce Injection.


As you mentioned earlier that you want to use pure javascript for getting current logged in user information. You can use Ajax Toolkit for this, it is a good one based on javascript. There you can do something like that:

<script src="../../soap/ajax/33.0/connection.js" type="text/javascript"></script>


    var user = sforce.connection.getUserInfo();
 var result = sforce.connection.query(
            "SELECT ID from User WHERE User.username='" + username + "'");
   var records = result.getArray("records");

sforce.connection.login("username", "password");


And for more help refer to this:



We achieve this the same way they do in the Success Community, which is with a separate VF page that has the sole purpose of generating JSON about the logged in as well as guest user. Then on any of my other pages, including the header of the community, we "import" that JSON using JS and can do what we want with it, like creating a user navigation menu.

Login to the Success Community to check out their userInfo page: https://success.salesforce.com/userinfo

Here is the page and controller for our page:

 <apex:page showHeader="false" standardStylesheets="false" sidebar="false"
     contentType="application/x-JavaScript; charset=utf-8"

And the controller:

public class HubUserInfoController {

public final static Integer TOU_APPROVAL_DAYS_AGO_FOR_NEW_USER = 90;
public final static String DEFAULT_AVATAR = 'profilephoto/005/T';

public String userInfoJson { get; private set; }

//public to allow this subclass to be accessible to a test class
public class HubUser {
    public String sessionId;
    public String fullName;
    public String email;
    public String userId;
    public Boolean isLoggedIn;
    public String profilePicUrl;
    public String profileOverviewUrl;
    public String profileFeedUrl;
    public String profileMyOrgUrl;
    public String profileBadgesUrl;
    public String recommendationsUrl;
    public Date TOUApprovalDate;
    public Boolean isNewUser;

public HubUserInfoController() {
    HubUser hu = getUserInfo();
    userInfoJson = JSON.serialize(hu);

private HubUser getUserInfo() {
    User runningUser = [
        SELECT    Name, Id, SmallPhotoUrl, Email, Profile.UserType, PUB_Terms_of_Use_Approval_Date__c
        FROM    User
        WHERE     Id = : UserInfo.getUserId()

    HubUser newHU = new HubUser();
    if (runningUser.Profile.UserType == 'Guest') {
        newHU.isLoggedIn = false;
    } else {
        newHU.sessionId = UserInfo.getSessionId();
        newHU.fullName = runningUser.Name;
        newHU.email = runningUser.Email;
        newHU.userId = runningUser.Id;
        newHU.isLoggedIn = true;
        newHU.TOUApprovalDate = runningUser.PUB_Terms_of_Use_Approval_Date__c;
        newHU.profilePicUrl = runningUser.smallPhotoUrl;
        newHU.profileOverviewUrl = '/_ui/core/userprofile/UserProfilePage?u=' + runningUser.Id + '&tab=sfdc.ProfilePlatformOverview';
        newHU.profileFeedUrl = '/_ui/core/userprofile/UserProfilePage?u=' + runningUser.Id + '&tab=sfdc.ProfilePlatformFeed';
        newHU.profileMyOrgUrl = '/_ui/core/userprofile/UserProfilePage?u=' + runningUser.Id + '&tab=My_Org';
        newHU.profileBadgesUrl = '/_ui/core/userprofile/UserProfilePage?u=' + runningUser.Id + '&tab=sfdc.Recognition';
        newHU.recommendationsUrl = '/_ui/core/chatter/recommend/RecommendationsPage?recType=GROUPS';

        if (newHU.TOUApprovalDate != null) {
            Date newUserCutoff = Date.today().addDays(-TOU_APPROVAL_DAYS_AGO_FOR_NEW_USER);
            if (newHU.TOUApprovalDate >= newUserCutoff) {
                newHU.isNewUser = true;
            } else {
                newHU.isNewUser = false;
        } else {
            newHU.isNewUser = true;

        if (!newHU.profilePicUrl.contains(DEFAULT_AVATAR)) {
            newHU.isNewUser = false;

    return newHU;

And then in the header of our community we grab the userInfo like this (this is using angular but you could do the same using jQuery or whatever:

(function() {
'use strict';

  .factory('userService', userService);

function userService($q, $http, $window) {
  var defaults = {
    isCached: false,
    logInUrl: '/publogin?startUrl=' + $window.location.pathname,
    isLoggedIn: false,
    urlPrefix: ''
  var userInfo = angular.copy(defaults);

  if ($window.location.href.indexOf('localhost') > -1) {
    userInfo.urlPrefix = 'https://powerofus.force.com';
  return {
    cache: userInfo,
    get: getUserSettings,
    flush: flush


  function getUserSettings() {
    var deferred = $q.defer();

    if (!userInfo.isCached) {
        .success(function(data, status, headers, config) {
          userInfo = angular.extend(userInfo, data);
          userInfo.isCached = true;

          $http.defaults.headers.common.Authorization = 'Bearer ' + data.sessionId;

        .error(function(data, status, headers, config) {
    } else {

    return deferred.promise;

  function flush() {
    userInfo = angular.copy(defaults);

Best approach is to use JS Remoting if you need to achieve this functionality in Javascript.

example: https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_js_remoting_example.htm

  • Doesn't that require visualforce? – Keith Mancuso Jun 4 '15 at 1:45
  • This is a static html footer on a standard Salesforce page, no apex or visualforce is allowed – Keith Mancuso Jun 4 '15 at 1:46
  • you can use the Salesforce connection.js api to query from Salesforce without using Visualforce page – Tuan Abdeen Jun 4 '15 at 1:53
  • Do you have info on how to do that? Never heard on connection.js – Keith Mancuso Jun 4 '15 at 1:54

use the below sample code:

function CallSOQL() { sforce.connection.sessionId = ‘{!$Api.Session_ID}’; try { alert(‘Select Name, Id From Account ORDER BY Name’); var AccountName=” TEST ACCOUNT”; var qr = sforce.connection.query(“SELECT id,name FROM Account where Name=’”+ AccountName +”‘”); var records = qr.getArray(“records”); alert(‘qr ‘+qr); } catch (error) { alert(error); } if (qr.size == 0) { alert(“No Record found.”); } else { for (var i=0;i

  • 1
    Interesting but isn't {!$Api.Session_ID} visualforce? – Keith Mancuso Jun 4 '15 at 1:55
  • 1
    You can use the following code for that: var result = sforce.connection.login("myname@mymail.com", "mypassword+mysecurityToken"); – Tuan Abdeen Jun 4 '15 at 1:57
  • Hmm but then your password and token are in plain text in the source code, not great. Thought of another way, thinking of setting up a visualforce page to return some json and just calling that page via ajax – Keith Mancuso Jun 4 '15 at 3:15
  • if you can use the VF its better with JS REmoteing. But you wanted a pure HTLM based solution right – Tuan Abdeen Jun 4 '15 at 4:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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