Вопрос

I am using code not much different from a default working one that is provided in a SharePoint Online app

'use strict';

var context = new SP.ClientContext("https://tenant-my.sharepoint.com");
var user = context.get_web().get_currentUser();

(function () {

$(document).ready(function () {
    getUserName();

});

// This function prepares, loads, and then executes a SharePoint query to get 
// the current users information
function getUserName() {
    context.load(user);
    context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}

// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess() {
    $('#message').text('Hello ' + user.get_title());
}

// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
    alert('Failed to get user name. Error:' + args.get_message());
}



}

})();

The only thing I modified is the way context is created var context = new SP.ClientContext("https://tenant-my.sharepoint.com"); instead of var context = SP.ClientContext.get_current(); following this post. Running the unchanged app works fine. Running the changed version gives the following error:

enter image description here

Это было полезно?

Решение

This error occurs since you are trying to access host web from app context.

SP.AppContextSite object is intended for that purpose, the below example demonstrates how to retrieve current user from host web:

var hostUrl = 'https://tenant-my.sharepoint.com';  //specify host web url

var scriptsUrl = hostUrl + '/' +  _spPageContextInfo.layoutsUrl + '/';
$.getScript(scriptsUrl + "SP.RequestExecutor.js", function (data) {

     getCurrentUser(hostUrl, 
        function(user) {
           console.log(user.get_loginName());    
        },
        function(sender, args) {
           console.log(args.get_message());
         });

});    



function getCurrentUser(hostUrl,success,error)
{
   var context =  SP.ClientContext.get_current();
   var appContextSite = new SP.AppContextSite(context, hostUrl);
   var web = appContextSite.get_web();

   var user = context.get_web().get_currentUser();
   context.load(user);
   context.executeQueryAsync(
     function(){
        success(user);
     },
     error);
}

About App permissions

An app for SharePoint uses permission requests to specify the permissions that it needs to function correctly. The permission requests specify both the rights that an app needs and the scope at which it needs the rights. These permissions are requested as part of the app manifest. The following picture demonstrates how to grant read access for an App enter image description here

Follow App permissions in SharePoint 2013 for a more details.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с sharepoint.stackexchange
scroll top