1 out of 1 rated this helpful - Rate this topic

How to: Access SharePoint 2013 data from remote apps using the cross-domain library

apps for SharePoint

Published: July 16, 2012

How to

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.

Table 1. Core concepts for the cross-domain library

Article title

Description

Apps for SharePoint overview

Learn about the new app model in SharePoint 2013 that lets you create apps, which are small, easy-to-use solutions for end users.

Data access options for apps in SharePoint 2013

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.

Client-side Cross-domain Security

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.

Work with the cross-domain library across different Internet Explorer security zones in apps for SharePoint

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.

Defining Document Compatibility

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:

  1. Create an app for SharePoint project and a web project.

  2. Modify the app manifest to allow communication from the remote app.

  3. 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.

Figure 1. Browser windows after running the solution

Resulting screens after going through this how to

To create the app for SharePoint and remote web projects

  1. 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.)

  2. 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

    App for SharePoint 2013 Visual Studio template
  3. Provide the URL of the SharePoint website that you want to use for debugging.

  4. Choose autohosted or provider-hosted as the hosting option for your app.

  5. 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

    App for SharePoint projects in Solution Explorer

To edit the app manifest file

  1. Double-click the AppManifest.xml file in Solution Explorer.

  2. Select the HTML page you created from the Start Page drop-down menu.

  3. In the Query String field, enter {StandardTokens}.

    Note Note

    {StandardTokens} is replaced by a number of query string parameters, including SPAppWebUrl, which the HTML page uses to obtain the app web URL.

  4. 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

    Manifest editor with suggested changes
    Important note Important

    Follow the remaining steps in this procedure only if you are developing a SharePoint-hosted app.

  5. Right-click the AppManifest.xml file in Solution Explorer, and select View code.

  6. 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

  1. Right-click the web project, and add a new HTML page.

  2. 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

  1. Make sure that the app for SharePoint project is set as the startup project.

  2. Press the F5 key.

    Note Note

    When you press F5, Visual Studio builds the solution, deploys the app, and opens the permissions page for the app.

  3. Choose the Trust It button.

  4. 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

    Host web title in the remote web page
Table 2. Troubleshooting the solution

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.

Did you find this helpful?
(1500 characters remaining)

Community Additions

ADD
© 2013 Microsoft. All rights reserved.