2

If I have a link to a document (which could be on another site than the current site), how can I extract a web relative url to the document from the url of the document? I am not sure how to do it because how would you differentiate a list name from another subsite name.

Does anyone know?

Thanks

1

Here's a slightly modified version of the code I created in an older question - this should help you achieve your task.

Reference: JSOM - get listitem by file URL

function getFileProperties(url, fileUrl) {
    var ctx = new SP.ClientContext(url); //get context
    var siteCollection = ctx.get_site(); //try get site to check if context is valid
    ctx.load(siteCollection);
    ctx.executeQueryAsync(
        function () {
            // context is valid - proceed 
            var relUrl = fileUrl.replace(_spPageContextInfo.siteAbsoluteUrl, '');  //convert to relative url
            alert('webrelativeurl is -- ' + relUrl);
            /*
            var file = ctx.get_web().getFileByServerRelativeUrl(relUrl);   //get file
            ctx.load(file, 'ListItemAllFields');

            ctx.executeQueryAsync(
                function () {
                    var listItem = file.get_listItemAllFields(); 
                    var comment = listItem.get_fieldValues()._Comments; 
                    var copyright = listItem.get_fieldValues().wic_System_Copyright;

                    $("#Description input").val(comment); //apply
                    $("#Copyright input").val(copyright);

                },
                function (sender, args) {
                    console.log(args.get_message()); //errorhandling
                }
            );   
        */             
        },
        function (sender, args) {
            //context is invalid - shrink url and try again
            if (url.indexOf("/") !== -1) {
                url = url.substr(0, url.lastIndexOf("/"));
                getFileProperties(url, fileUrl); //recursive call
            }
            //else - the url is not compatible
        }
    );
}

var imageUrl = 'http://yourfullimageurl/sites/sc/weba/webb/images/imagea.jpg'

//get image file properties
getFileProperties(imageUrl, imageUrl);

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.