Ok I've already opened a subject like this, but this time I have no hairs left so I'm gonna summarize my knowledge on this issue, clearly, and hope that someone could help me.
Goal
I try to hide a node of the left navigation menu if the user is not part of the SP admin group.
Facts
To do this, I use jQuery on a custom .js file. I succeed to get if the user is admin or not, the problem is not here. But when I try to select the particular node to hide it, is works, on some pages. On others, it won't work.
I'm using SharePoint Foundation 2013.
Code
Here is my function to be called for every page loads :
function checkAdminRights() {
var userId = _spPageContextInfo.userId;
var requestHeaders = { "accept" : "application/json; odata=verbose" };
$.ajax({
url : _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(7)/users/getbyid(" + userId + ")",
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : userAdmin,
error : userNotAdmin
});
function userAdmin(data, request) {
console.log("user admin");
var groupName = data.d.LoginName;
}
function userNotAdmin(error) {
console.log("user not admin");
$("ul.ms-core-listMenu-root li.static").each(function() {
console.log("found !");
if($(this).find("span.menu-item-text").text().indexOf("Administration") >= 0) {
$(this).hide();
}
});
}
}
I tried to launch this function with every single damn ways :
$.getScript("/_layouts/15/SP.UserProfiles.js");
SP.SOD.executeOrDelayUntilScriptLoaded(checkAdminRights, 'SP.UserProfiles.js');
// or
$.getScript("/_layouts/15/SP.UserProfiles.js");
_spBodyOnLoadFunctionNames.push('checkAdminRights');
In or out the following calls :
$(window).load(function () {}
// or
$(document).ready(function() {}
I can add that :
- sp.js is already included in my pages, I can see it from the web developper toolbox of my browser (Firefox)
- I cleared the cache between tries
- I tried the conflict avoidance, by changing the aliases of jQuery "$" to "$jq", not changed anything.
Logs
In the console logs I can see that my function checkAdminRights is called properly and always execute the right callback. So if the user isn't admin, at each page load is see "user not admin". BUT, my .each(... loop is never accessed on some pages, in spite of that the HTML tag is existing !
Question
Why the hell, I can hide the node when loading for example the homepage ? But not for my Wiki pages, or a lot of others ?
I suspect the sp.js not to be included in the content of the page but into the master page. So it don't have the scope to reach my menu elements. I'm saying this because I've noticed that every pages where I put a Custom Script WebPart and I reference sp.js into, my code works for these pages.
Any help is appreciated, this thing is driving me crazy.