Using cross-domain library with SharePoint 2013 apps

 Jan 16, 2015

 

When you create a cloud-based app in SharePoint, the pages of your app will be in a different domain than the app web that contains lists and libraries to be used by the app. In today's blog post, I will show you a technique to circumvent the fact that the browser would not allow JavaScript code running in the pages of your app to access the data stored in the lists and libraries with a different domain. Note that in the case of a SharePoint-hosted app, this is not an issue because the start page of your app is running in the app web domain and so you can write JavaScript code that access the lists and libraries that are in the same domain. A cloud-based app is deployed in an external web server and having a corresponding app web in SharePoint is not required. In this case, all the data for the app would be stored in an external database maintained by the remote host of your app. But even a cloud-based app can optionally have an app web like SharePoint-hosted apps always have. That's the scenario we are addressing here. The cross-domain library is a JavaScript library included with SharePoint 2013 with which a cloud-hosted app can issue client-side calls to the SharePoint host environment from pages in the remote web. This library is contained in the file SP.RequestExecutor.js which is located in the LAYOUTS folder. You can manually copy that file to the remote app's hosting web site or load the script dynamically from its original location in SharePoint as shown below:

$.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js", execCrossDomainCall);

The query string parameters passed to the page in your remote app are automatically populated with the host web and the app web urls. You need to retrieve those parameters by parsing the document.URL. We are using the jQuery function getScript to load the script and then execute the function execCrossDomainCall  as we show next:

function execCrossDomainCall ()  {    var executor;     // Initialize your RequestExecutor object.     //appweburl was retrieved from the query string    executor = new SP.RequestExecutor(appweburl);    … 

jQuery gives the guarantee that the code in the function above is only executed after the script with the cross-domain library is completely loaded. Now the executor object is the entry point for your app to make cross-domain calls retrieving and/or manipulating data available in the lists and libraries deployed into the app web. The following code snippet shows how:

executor.executeAsync(     url: appweburl + "_api/web/list/getByTitle('Customers')/items"     method: "GET",     headers: { "Accept": "application/json;odata=verbose" },     success: function(data) {  //process the returned data };     error: function (data, errorCode, errorMessage) { //give feedback in case of an error }  }

An example of how you would process the returned data follows:

success: function(data)       var html = [];       html.push(" "+
ID Name Address
     
      ");       var results = data.d.results;       for(var i=0; i<results.length; i++) {            html.push("" + results[i].ID + "";            html.push("" + results[i].Name+ "" ;            html.push("" + results[i].Address+ "" ;      };     html.push("");     $('#displayResults').html(html.join('');  }

Note that we are using jQuery to insert the HTML content into a place holder with the ID displayResults in the page. In the example above, we used the GET verb but we could use other verbs like POST to insert new customers, PUT to update an existing customer or DELETE to remove a customer. To learn more about client-side coding and SharePoint apps we recommend the New Horizons' Training course '20488 – Developing Microsoft SharePoint Server 2013 Core Solutions'.

How do your Excel skills stack up?   

Test Now  

About the Author:

Newton Godoy  

With over 17 years of in-class training experience and over 16 years of industry experience, Newton offers students a wealth of real-world technical knowledge and expertise in the areas of .NET application development, SQL Server and SharePoint Server. After spending several years lecturing as a professor, Newton found his true calling and began his career as a MCT. He worked as a technical trainer for some of Brazil’s and Australia’s largest corporate training organisations before finally finding a home with New Horizons where he is now one of our top trainers. Newton brings a thorough mentoring capability to the classroom where he can advise on technical issues and challenges often beyond the scope of the course curriculum. His combination of technical knowledge and instructor experience make him one of the most respected instructors within the IT training industry.

Read full bio
top