0

Suppose I have the URL to a file. How can I determine the path to the (sub)site (spweb) it is hosted on, using JavaScript.

Here are some examples. Bolded text is what I am looking for:

https://tenant.sharepoint.com/library1/file.jpg

https://tenant.sharepoint.com/sites/site1/library1/file.jpg

https://tenant.sharepoint.com/sites/site1/library1/folder1/file.jpg

https://tenant.sharepoint.com/sites/site1/library1/folder1/folder2/file.jpg

https://tenant.sharepoint.com/sites/site1/subsite1/library1/file.jpg

https://tenant.sharepoint.com/teams/site1/subsite1/library1/folder1/file.jpg

https://tenant.sharepoint.com/teams/site1/subsite1/subsite2/library1/file.jpg

2

Try with following JS code

<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
var owebsite;
var documentPath = "http://sharepointsite/subsite/Shared%20Documents/Forms/AllItems.aspx";
documentPath = documentPath.substring(0, documentPath.lastIndexOf('/')) + "/_api/contextinfo";
$.ajax({
    url: documentPath,
    type: "POST",
    contentType: "application/x-www-url-encoded",
    dataType: "json",
    headers: {
        "Accept": "application/json; odata=verbose",
    },
    success: function (data) {
        if (data.d) {
            var webUrl = data.d.GetContextWebInformation.WebFullUrl;
SP.SOD.executeFunc('sp.js','SP.ClientContext',function(){
            var clientContext = new SP.ClientContext(webUrl);
            owebsite = clientContext.get_web(); 
            clientContext.load(owebsite);
            clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceed),Function.createDelegate(this, this.onQueryFailed));
        });
        }
    },
    error: function (err) {
       alert(JSON.stringify(err));
    }
});

onQuerySucceed = function () {
    alert(owebsite.get_url());
};

onQueryFailed = function (sender, args) {
    alert(args.get_message());
};
</script>
  • This works. Clever! – rlv-dan Dec 13 '16 at 9:48
0

Assuming all your site/subweb have "Library1" named document library and all the files is contained in "Library1". you can try something like below:

var t ="https://tenant.sharepoint.com/sites/site1/library1/folder1/folder2/file.jpg"
t.substring(0,t.indexOf("library1")-1)
  • True, but Library1 was just an example. I would like to find a solution that works regardless of names. – rlv-dan Dec 13 '16 at 8:00
0

It should be SPContext.Current.Web.Url

  • This would only work if I am on the particular site. I should have clarified that I need it to work regardless of what site I am visiting. – rlv-dan Dec 13 '16 at 7:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.