How to: Access SharePoint 2013 data from remote apps using the cross-domain library
Published: July 16, 2012
Learn how to access data in a SharePoint website from a remote app by using the cross domain library in SharePoint 2013.
Applies to: apps for SharePoint | Office 365 | SharePoint Foundation 2013 | SharePoint Server 2013
When you build apps for SharePoint, you usually have to incorporate data from various sources. But for security, there are blocking mechanisms that prevent communication with more than one domain at a time. When you use the cross-domain library, the webpages in your app can access data in your remote domain and the SharePoint domain.
The cross-domain library is a client-side alternative in the form of a JavaScript file (SP.RequestExecutor.js) that is hosted in the SharePoint website that you can reference in your remote app. The cross-domain library lets you interact with more than one domain in your remote app page through a proxy. It is a good option if you like your app code to run in the client instead of on the server, or if there are connectivity barriers, such as firewalls, between SharePoint and your remote infrastructure. You can access data in the host web—for example, you can access lists that end users interact with regardless of your app. Or you can access data in the app web, which only exists when your app is deployed. Tenant-scoped apps can also access other site collections and websites as long as the app has permissions. This article guides you through the process of building an app that reads the host web title and displays it in a remote webpage.
To follow the steps in this example, you need the following:
-
Visual Studio 2012
-
Office Developer Tools for Visual Studio 2012
-
A SharePoint 2013 development environment (app isolation required for on-premises scenarios)
For guidance on how to set up a development environment that fits your needs, see Get started developing apps for SharePoint.
Core concepts to know before using the cross-domain library with apps for SharePoint
The following table lists some useful articles that can help you understand the concepts involved in a cross-domain scenario for apps.
|
Article title |
Description |
|---|---|
|
Learn about the new app model in SharePoint 2013 that lets you create apps, which are small, easy-to-use solutions for end users. |
|
|
Learn about data access options for apps for SharePoint. This article provides guidance on the high-level alternatives you have when working with data in your app. |
|
|
Host webs, app webs, and SharePoint components in SharePoint 2013 |
Learn about the distinction between host webs and app webs. Find out which SharePoint 2013 components can be included in an app for SharePoint, which components are deployed to the host web, which components are deployed to the app web, and how the app web is deployed in an isolated domain. |
|
Explore cross-domain threats and use cases, and security principles for cross-origin requests, and weigh the risks for developers to enhance cross-domain access from web applications that run in the browser. |
|
|
Learn how to use the cross-domain library in SharePoint 2013 when the host web and app pages are in different security zones in Windows Internet Explorer. |
|
|
The cross-domain library requires a document mode of IE8 or above. You can set your page’s document mode by using the <!DOCTYPE html> or <meta http-equiv="X-UA-Compatible" content="IE=8"> elements. At design time you can use Internet Explorer developer tools (F12) to determine or change the document mode in which your page is rendering. |
To read data from the host web, you must do the following:
-
Create an app for SharePoint project and a web project.
-
Modify the app manifest to allow communication from the remote app.
-
Create an HTML page that uses the cross-domain library to query the title property.
Figure 1 shows the browser window with the host web’s title in the SharePoint website and in the remote app.
To create the app for SharePoint and remote web projects
-
Open Visual Studio 2012 as administrator. (To do this, right-click the Visual Studio 2012 icon in the Start menu, and choose Run as administrator.)
-
Create a new project using the App for SharePoint 2013 template.
Figure 2 shows the location of the App for SharePoint 2013 template in Visual Studio 2012, under Templates, Visual C#, Office SharePoint, Apps.
Figure 2. App for SharePoint 2013 Visual Studio template
-
Provide the URL of the SharePoint website that you want to use for debugging.
-
Choose autohosted or provider-hosted as the hosting option for your app.
-
After the wizard finishes, you should have a structure in Solution Explorer that resembles Figure 3.
Figure 3. App for SharePoint projects in Solution Explorer
To edit the app manifest file
-
Double-click the AppManifest.xml file in Solution Explorer.
-
Select the HTML page you created from the Start Page drop-down menu.
-
In the Query String field, enter {StandardTokens}.
Note
{StandardTokens} is replaced by a number of query string parameters, including SPAppWebUrl, which the HTML page uses to obtain the app web URL.
-
Add a Read permission request with scope http://sharepoint/content/sitecollection/web.
Figure 4 shows the manifest editor after the suggested changes.
Figure 4. App manifest in the manifest editor
Important
Follow the remaining steps in this procedure only if you are developing a SharePoint-hosted app.
-
Right-click the AppManifest.xml file in Solution Explorer, and select View code.
-
Copy the following app principal definition, and use it to replace the default AppPrincipal element that is already there.
<AppPrincipal> <Internal AllowedRemoteHostUrl="~remoteAppUrl"/> </AppPrincipal>The AllowedRemoteHostUrl attribute is used to specify the remote domain. Autohosted and provider-hosted apps do not require the AllowedRemoteHostUrl attribute. The ~remoteAppUrl resolves to the remote app URL. For more information about tokens, see Explore the app manifest and the package of an app for SharePoint.
To add a new HTML page that uses the cross-domain library
-
Right-click the web project, and add a new HTML page.
-
Copy the following markup and paste it in the HTML page. The markup performs the following tasks:
-
Loads the AJAX library from the Microsoft CDN (Content Delivery Network).
-
Loads the jQuery library from the Microsoft CDN.
-
Provides a placeholder for the host web title.
-
Extracts the app web URL from the query string.
-
Loads the cross-domain library JavaScript using the getScript function in jQuery.
-
Issues a Representational State Transfer (REST) call to the host web title property endpoint.
-
Handles successful completion, rendering the title in the remote webpage.
-
Handles errors, rendering the error message in the remote webpage.
<!DOCTYPE html> <html> <head> <title>Cross-domain sample</title> </head> <body> <div> <!-- This is the placeholder for the host web title --> The host web title is: <label id="HostwebTitle"></label> </div> <script src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js" type="text/javascript"> </script> <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"> </script> <script type="text/javascript"> var hostweburl; var appweburl; // Load the required SharePoint libraries. $(document).ready(function () { //Get the URI decoded URLs. hostweburl = decodeURIComponent( getQueryStringParameter("SPHostUrl") ); appweburl = decodeURIComponent( getQueryStringParameter("SPAppWebUrl") ); // Resources are in URLs in the form: // web_url/_layouts/15/resource var scriptbase = hostweburl + "/_layouts/15/"; // Load the js file and continue to the // success event handler. $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest); }); // Function to prepare and issue the request to get // SharePoint data. function execCrossDomainRequest() { var executor; // Initialize the RequestExecutor with the app web URL. executor = new SP.RequestExecutor(appweburl); // Issue the call against the host web. // To get the title using REST we can hit the endpoint: // app_web_url/_api/SP.AppContextSite(@target)/web/title?@target='siteUrl' // The response formats the data in the JSON format. // The functions successHandler and errorHandler attend the // success and error events respectively. executor.executeAsync( { url: appweburl + "/_api/SP.AppContextSite(@target)/web/title?@target='" + hostweburl + "'", method: "GET", headers: { "Accept": "application/json; odata=verbose" }, success: successHandler, error: errorHandler } ); } // Function to handle the success event. // Prints the host web's title to the page. function successHandler(data) { var jsonObject = JSON.parse(data.body); document.getElementById("HostwebTitle").innerHTML = "<b>" + jsonObject.d.Title + "</b>"; } // Function to handle the error event. // Prints the error message to the page. function errorHandler(data, errorCode, errorMessage) { document.getElementById("HostwebTitle").innerText = "Could not complete cross-domain call: " + errorMessage; } // Function to retrieve a query string value. // For production purposes you may want to use // a library to handle the query string. function getQueryStringParameter(paramToRetrieve) { var params = document.URL.split("?")[1].split("&"); var strParams = ""; for (var i = 0; i < params.length; i = i + 1) { var singleParam = params[i].split("="); if (singleParam[0] == paramToRetrieve) return singleParam[1]; } } </script> </body> </html>This example uses the AppContextSite REST endpoint to reference the host web. By using the AppContextSite REST endpoint and JavaScript object model class, you can access SharePoint websites other than the app web. For full code samples that reference the host web, see the following:
-
To build and run the solution
-
Make sure that the app for SharePoint project is set as the startup project.
-
Press the F5 key.
Note
When you press F5, Visual Studio builds the solution, deploys the app, and opens the permissions page for the app.
-
Choose the Trust It button.
-
Choose the app icon on the Site Contents page.
Figure 5 shows the host web title in the remote webpage.
Figure 5. Host web title in the remote webpage
|
Problem |
Solution |
|---|---|
|
Visual Studio does not open the browser after you press the F5 key. |
Set the app for SharePoint project as the startup project. |
|
Unhandled exception SP is undefined. |
Make sure you can access the SP.RequestExecutor.js file in a browser window. |
|
Error message: The required functionalities are not supported by your browser. Please make sure you are using IE 8 or above, or other modern browser. Please make sure the 'X-UA-Compatible' meta tag is set to be 'IE=8' or above. |
The cross-domain library requires a document mode of IE8 or above. In some scenarios, the document mode is set to IE7 by default. You can use the Internet Explorer developer tools to determine and change the document mode of your page. For more information, see Defining Document Compatibility. |
This article demonstrated how to access SharePoint data from your remote app. As a next step, you can learn about other data access options that are available in apps for SharePoint. To learn more, see the following:
-
Code sample: Get the host web title using the cross-domain library (REST)
-
Code sample: Get the host web title using the cross-domain library (JSOM)
-
Code sample: Get list items by using the cross-domain library (REST)
-
Code sample: Get list items by using the cross-domain library (JSOM)
-
Code sample: Use the chrome control and the cross-domain library (REST)
-
Code sample: Use the chrome control and the cross-domain library (JSOM)
-
Code sample: Use custom actions and the cross-domain library to order books
-
How to: Create a custom proxy page for the cross-domain library in SharePoint 2013
-
How to: Query a remote service using the web proxy in SharePoint 2013