1

I am currently trying to retrieve the current URL of a document library using JavaScript.

My ultimate goal is to un-hide a web part when the user clicks a specific folder.

Right now,

My code so far:

ExecuteOrDelayUntilScriptLoaded(loadFolderView, "sp.js");

function unhidepart() {
    var unhideWP = document.getElementById("MSOZoneCell_WebPartWPQ1");
    unhideWP.style.display="block";
}

function hidepart() {
    var hideWP = document.getElementById("MSOZoneCell_WebPartWPQ1");
    hideWP.style.display="none";
}

function loadFolderView() {
    hidepart();

    var folderUrl = "https://example.com/sites/doclib/Forms/AllItems.aspx?RootFolder=%2Fsites%2Fdoclib%2FFOLDER%20NAME";
    var ctx = new SP.ClientContext.get_current();
    var site = ctx.get_site();
    ctx.load(site);
    ctx.executeQueryAsync(
        function () {
            var url = site.get_url();
            console.log(url);
            if (url == folderUrl) {
               unhidepart();
            }
        },
        function (sender, args) {
            console.log('error');
        });             

}

Right now it only logs /sites/doclib and I'm not sure how to get the full URL of the folder.

Any help or suggestions to make this easier would be very appreciated.

3
  • Which version of SharePoint you are using? Where & how are you adding this code? Are you adding this code on document library view page using content editor/script editor web part? Commented Oct 20, 2021 at 10:54
  • 2016. Yes, using the script editor web part to add this to a document library view page.
    – michelle
    Commented Oct 21, 2021 at 9:33
  • You can get current URL in browser using var pageUrl = window.location.href;. does this work for you? Commented Oct 21, 2021 at 10:25

1 Answer 1

0

You can get the relative URL of current folder using:

ctx.rootFolder

Example:

var rootFolder = decodeURIComponent(ctx.rootFolder);
console.log(rootFolder);

Output:

enter image description here

Note: This is a default ctx variable loaded on SharePoint list/library view pages & not the ctx variable you defined in your code at var ctx = new SP.ClientContext.get_current();.


Also, You can get current URL in browser tab (includes complete URL with query parameters) using simple JavaScript:

var pageUrl = window.location.href;
console.log(pageUrl);

Output:

enter image description here

Further, you can split the URL & extract the necessary parts as per your requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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