Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / productivity / SharePoint

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

5.00/5 (1 vote)
11 Nov 2014CPOL 10.8K  
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.

image

Provider hosted involves two hosting domains (example: 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.

Example

https://host.azurewebsites.net/pages/default.aspx?SPHostUrl=https:%2F%2Fsphost.sharepoint.com%2Fsites%
2app&SPLanguage=en-US&SPClientTag=0&SPProductNumber=16.0.3417.1223&SPAppWebUrl=https:%2F%
2Fsphost-265535272e9c8d.sharepoint.com%2Fsites%2Fapp%
2FSample&Source=https://app.azurewebsites.net/pages/default

We can get AppWebUrl by accessing Url parameter. The following code snippet shows a utility function for getting Url parameter.

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

JavaScript
var spAppWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
var ctx = new SP.ClientContext(spAppWebUrl);
var factory = new SP.ProxyWebRequestExecutorFactory(spAppWebUrl);
ctx.set_webRequestExecutorFactory(factory);
var web = ctx.get_web();
 
ctx.executeQueryAsync(
    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.

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)