Here is a snippet to save your day.
There are many snippets out there showing you how to do cross domain calls, but none of them complete.
Here is a sample to access host web components from a SharePoint hosted app or add in.
Keywords: SharePoint, access host web, sharepoint online, JSOM, CSOM, SharePoint hosted app, Office 365.
'use strict';
//URLs
var hostweburl;
var appweburl;
var context;
var appContextSite;
var factory;
var context = SP.ClientContext.get_current();
var appContextSite;
var rootweb ;
var roleDefinitions ;
(function () {
$(document).ready(function () {
hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
var scriptbase = hostweburl + "/_layouts/15/";
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$('#message').append(" Getting Scripts..
");
$.getScript(scriptbase + "SP.js",
function () { $.getScript(scriptbase + "SP.RequestExecutor.js", loadRoleDefinition); }
);
}
);
});
// This function prepares, loads, and then executes a SharePoint query
function loadRoleDefinition() {
context = new SP.ClientContext(appweburl);
factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
rootweb = appContextSite.get_web();
roleDefinitions = rootweb.get_roleDefinitions();
context.load(appContextSite);
context.load(rootweb);
context.load(roleDefinitions);
context.executeQueryAsync(onGetRoleDefinitionSuccess, onGetRoleDefinitionFail);
}
function onGetRoleDefinitionSuccess() {
var permissionExists = false;
var roleDefinitionsEnum = roleDefinitions.getEnumerator();
while (roleDefinitionsEnum .moveNext()) {
var temp = roleDefinitionsEnum.get_current();
$('#message').append(temp.Name + "
");
}
}
function onGetRoleDefinitionFail(sender, args) {
$('#message').text('Failed to get Role Definitions. Error:' + args.get_message());
}
})();
Comments