Wednesday, June 4, 2014

When working with SharePoint App the architecture of App must be cleared in mind. Apps gets deployed on special web which is called App web and where App gets installed is known as Host web. So whenever you work with the current context, this context is nothing but the context of the App web and not Host web where you are going to install App. Another thing you need to consider is cross-site or cross domain requests. It’s not always the case that  app web of App and host web are in same domain.

Now the question will come  in your mind that how I can write a App which will access list and list data of host site? You don’t have to worry about it now because you have cross-domain library: SP.RequestExecutor.js.  This library lets you get data from more than one domain and web applications.

In this blog we will see how you can access SharePoint data using cross-domain library. Now if you use below ECMA code which is normal ECMA code then it will return data from the App web. So with below ECMA script you will see lists and libraries of App web.

        var context = new SP.ClientContext.Current();         
        var web = appContextSite.get_web();
        var lists = web.get_lists();
        context.executeQueryAsync(onSuccess, onFail);

Now to get data from Host web app you need to use cross-domain library as follows: 
First you have to get the URLs of both app Web and Host web by using following code lines:

        var hostweburl = getQueryStringParameter("SPHostUrl");
        var appweburl = getQueryStringParameter("SPAppWebUrl");
        hostweburl = decodeURIComponent(hostweburl);
        appweburl = decodeURIComponent(appweburl);

After getting App web and Host web URL’s next step is getting cross-domain library as follows:

        var scriptbase = hostweburl + "/_layouts/15/"; 
        $.getScript(scriptbase + "SP.Runtime.js",
        function () {
                        $.getScript(scriptbase + "SP.js",
                        function () { $.getScript(scriptbase + "SP.RequestExecutor.js", YourMethodName); }

Remember one thing use host web URL while getting library.  Now once library is loaded you are ready to create/get context objects but before that load Web Requester Executor factory. You will get is as follows:

        var context = new SP.ClientContext(appweburl);
        var factory =
            new SP.ProxyWebRequestExecutorFactory(
        var appContextSite = new SP.AppContextSite(context, hostweburl);

Now use your familiar calls to get information:

        web = appContextSite.get_web();
        lists = web.get_lists();
        context.executeQueryAsync(onSuccess, onFail);

In this way you can write cross-site /cross-domain client side scripts. 

Happy Coding :)


Post a Comment