Cross domain calls are blocked by modern web browsers due to security concerns. This is a common issue in web based development and is particularly relevant due to the nature of SharePoint hosted Apps. For example, when accessing data in the parent web (http://consoto.sharepoint.com
) from an App (hosted at http://apps.sharePoint.com/SPApp
) the calls will be blocked. To get round this you can use the SP.RequestExecutor.js
script to relay messages to SharePoint from within the same domain.
Example
function getListItems(hostUrl,appWebUrl, listTitle,success,error)
{
var url = appWebUrl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('" + listTitle + "')/items?@target='" + hostUrl + "'";
var executor = new SP.RequestExecutor(appWebUrl);
executor.executeAsync(
{
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var data = JSON.parse(data.body);
success(data.d.results);
},
error: error
});
}
Usage
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var appWebUrl = getParameterByName('SPAppWebUrl');
var hostUrl = getParameterByName('SPHostUrl');
var scriptbase = hostUrl + '/_layouts/15/';
$.getScript(scriptbase + "SP.RequestExecutor.js", function (data) {
getListItems(hostUrl,appWebUrl, 'Tasks',function(data){
//print list items properties
data.forEach(function(item){
console.log(item.Title);
});
},
function(error){
//error handling goes here...
});
});
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
Follow App permissions in SharePoint 2013 for a more details.