Tuesday, November 11, 2014

How to initialize the SharePoint Client Context in SharePoint Apps (Provider Hosted / SharePoint Hosted) using JSOM (JavaScript Object Model)


SharePoint Provider Hosted Apps

First of all we need to understand the SharePoint Provider Hosted hosting blocks.


Provider hosted involves two hosting domains (ex host, sphost). thus request sending to host to sphost considering as cross domain request.

For cross domain request we need to provide SPAppWebUrl to initialize the context. SPAppWebUrl  is available in Url.



we can get AppWebUrl by accessing Url parameter. following shows a utility function for getting Url parameter.

function getQueryStringParameter (paramToRetrieve) = {
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve)
            return singleParam[1];
    return "";

This will initiate the client context using remote web Url.

var spAppWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
var ctx = new SP.ClientContext(spAppWebUrl);
var factory = new SP.ProxyWebRequestExecutorFactory(spAppWebUrl);
var web = ctx.get_web();
    function () {
           alert("sucess"); },
    function (a, b) {
           alert("error");  }


SharePoint Hosted Apps

SharePoint Hosted app does not have separate hosting server. SharePoint hosted apps run on the same SharePoint server. thus client context initialization does not need to provide the Url.

var ctx = new SP.ClientContext.get_current();
var web = _sa.ctx.get_web();
    function () {
           alert("sucess"); },
    function (a, b) {
           alert("error");  }
Post a Comment