0

Basically, what I want to achieve is to hide particular elements in all SharePoint sites within a single farm.

What I did is I created a SiteCode.js file inside the Site Assets folder and filled it with the following code:

function CallClientOM() {
    var context = new SP.ClientContext.get_current();
    this.website = context.get_web();
    this.currentUser = website.get_currentUser();
    context.load(currentUser);
    context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
    alert(currentUser.get_loginName());
}

function onQueryFailed(sender, args) {
    var siteActionsMenu = document.querySelectorAll("#siteactionid")[0];
    siteActionsMenu.parentNode.removeChild(siteActionsMenu);

    var topNavLinks = document.querySelectorAll(".brc-nav-toplinks-right")[0];
    topNavLinks.parentNode.removeChild(topNavLinks);
}

//window.onload = CallClientOM();

/*
$(document).ready(function() {
    CallClientOM();
});
*/

When I load this function inside Google Chrome Developer Tool (CallClientOM()) I am actually able to hide those elements and see changes right away. But the problem is I cannot achieve this once the site loads.

I have tried two methods which are at the bottom (as comments).

I've also tried to wrap all code within $(document).ready(function() {} function, but with no success. It seems that I'm missing something or doing incorrectly.

How do I load this function once the site loads (without using Developer Tools or anything) before site content?

4 Answers 4

2

You need to use

_spBodyOnLoadFunctionNames.push("CallClientOM");

because jQuerys ready function isn't reliable in SharePoint

http://www.stephanrocks.com/2011/10/05/_spbodyonloadfunctionnames-in-sharepoint-vs-jquerys-document-ready/

or wait for sp.js:

SP.SOD.executeOrDelayUntilScriptLoaded(loadContext, 'sp.js');
    function loadContext() {
        var context = SP.ClientContext.get_current();
        var web = context.get_web();
    }

There is way more to understand

read all 6 blogs by Hugh Wood: http://www.spcaf.com/blog/sharepoint-javascript-context-dev-part-1/

2
  • Thank you for suggestion. I suppose it did worked but it appears that once the site page loads it throws an error in the 2nd line: var context = new SP.ClientContext.get_current(); which says "Uncaught TypeError: Cannot read property 'get_current' of undefined". It's strange because when I try to run this CallClientOM in the console I don't get any errors...
    – Mangustas
    Dec 1, 2015 at 10:18
  • Because once you start typing in the console SP.js has loaded.. and jQuerys ready does not fire at the correct time. You have to wait for SP.js Dec 1, 2015 at 10:25
0
this.getWebUserData = function (){
    this.context = new SP.ClientContext.get_current();
    this.web = this.context.get_web();
    this.currentUser = this.web.get_currentUser();
    this.currentUser.retrieve();
    this.context.load(this.web);

    this.context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), 
                                   Function.createDelegate(this, this.onFailureMethod));
}
// this will return Currently log in User
this.onSuccessMethod = function (){
    alert(this.currentUser.get_title());
}

//will show alert Message is failed to retrieve Information
this.onFailureMethod = function (){
    alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

ExecuteOrDelayUntilScriptLoaded(getWebUserData, "sp.js"); 
0
$(document).ready(function(){ var thisUserAccount=$().SPServices.SPGetCurrentUser({fieldName: "Title",debug: false});   $('#lblfrom').text(thisUserAccount); });
0

I added this script into my masterpage for getting the users department and after that I change a link in the navigation. Here the beginning of it and how to get the user.

<script type="text/javascript">

$(document).ready(function() {
var loginName = "";
var userid = _spPageContextInfo.userId;

function GetCurrentUser() {

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";

var requestHeaders = { "accept" : "application/json;odata=verbose" };

$.ajax({
  url : requestUri,
  contentType : "application/json;odata=verbose",
  headers : requestHeaders,
  success : onSuccessA,
  error : onErrorA
});
}

function onSuccessA(data, request){

    // alert("Success One");
    // cutting of i:0#.w|

    //console.log(data.d);
    //var emailAdresse = data.d.Email;
    //alert(emailAdresse);

    var loginName = data.d.LoginName.split('|')[1];

    var repOne = "%5C";  
    var repTwo = "%2E";
    // alert("before replace: " + loginName);

    loginName = loginName.replace(/\\/g, repOne); // replace \ with %5C
    loginName = loginName.replace(/\./g, repTwo); // replace . with %2E

    // alert("after replace: " + loginName);

    GetCurrentUserDepartment(loginName); // call next function to get department. Pass the loginname into the function
}

function onErrorA(error) {

  alert(error);
}

GetCurrentUser();

});
</script>

Hope this will help you a little.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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