Monday, October 13, 2014

SharePoint 2013: Use the cross-domain library in a tenant-scoped app (JSOM)

You will find code sample for cross-domain library in a tenant-scope app based on REST call on Microsoft site but not based on JSOM. I am not very much comfortable in REST calls so i decided to created similar example in JSOM.

Download sample code from here and just replace JavaScript in CrossDomainExec.js with below script




var web;
var hostweburl;
var appweburl;

function execCrossDomainRequest() {
    hostweburl =
         decodeURIComponent(
             getQueryStringParameter('SPHostUrl')
     );
    appweburl =
        decodeURIComponent(
            getQueryStringParameter('SPAppWebUrl')
     );

    var scriptbase = hostweburl + '/_layouts/15/';

    $.getScript(scriptbase + 'SP.Runtime.js',
        function () {
            $.getScript(scriptbase + 'SP.js',
                function () { $.getScript(scriptbase + 'SP.RequestExecutor.js', GetWebInfo); }
            );
        }
    );
}

function getQueryStringParameter(param) {
    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] == param) {
            return singleParam[1];
        }
    }
}

function GetWebInfo() {
    var context;
    var factory;
    var appContextSite;
   
    context = new SP.ClientContext(appweburl);
    factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    context.set_webRequestExecutorFactory(factory);
    //appContextSite = new SP.AppContextSite(context, hostweburl);
    appContextSite = new SP.AppContextSite(context, document.getElementById("sitecoll1").value);//host url replaced by site collection url

    var web = appContextSite.get_web();
    context.load(web);

    context.executeQueryAsync(
        successHandler, errorHandler
    );

    function successHandler() {
        var oli = document.createElement("li");

        oli.innerText = web.get_title() + " (" + web.get_url() + ")";
        document.getElementById("WebTitles").appendChild(oli);
    }

    function errorHandler(sender, args) {
        document.getElementById("WebTitles").innerText = "Could not complete cross-domain call: " + args.get_message();
    }
}

2 comments:

  1. Hi,
    I tried this code, but it didnt work. I have admin access on the target site collection and yet when i try to create the web object i get an error saying "Access Denied. Permission required."

    ReplyDelete
    Replies
    1. My first question to you is, How you deployed your App? This is tenant scope App so you should deploy it through 'App Catalog' but not on 'Developer Site' . Second make sure you have given Tenant read permission in AppManifest.

      Checkout my other article on 'Access Denied' issue http://sandippatilblog.blogspot.com/2013/10/acess-data-from-other-site-collection-in-sharepoint-hosted-apps.html

      Delete