Sharepoint - how to get site collection url from SharePoint Hosted App

In your App url there are various Query String Parameters as shown here. That already containts the site collection url.

The Query String paramter "SPHostUrl" will give you the site collection URl.

In order to get that URL you can use following code

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];
}
}

Just use this code as

hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl")

Now this hostweburl will contain your site collection URL. For code reference you can see here


From your SharePoint Hosted app what you can get context of host web and fetch the url of site collection You can use RequestExecutor for cross domain request as

 $.getScript(hostUrl + "/_layouts/15/" + "SP.RequestExecutor.js", GetSiteUrl);

and then fetch URL of sitecollection using bellow function

function GetSiteUrl() {
    var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    var currentcontext = new SP.ClientContext()
    var hostcontext = new SP.AppContextSite(currentcontext, hostUrl);
    var site = hostcontext.get_site();
    currentcontext.load(site);
    currentcontext.executeQueryAsync(function (s, a) {
        sitecollectionurl = site.get_url()

    });
} 

Hope this will help you!

Tags:

Url