Buy Me a Coffee

Buy Me a Coffee!

Friday, January 20, 2017

SharePoint base url in JS

I am working on a SharePoint based application that uses Angular 1.0 to deliver the UI and one of the things that we do as part of our development process is run the code locally, accessing the data from the SharePoint server.  A colleague wrote this to get the base url.  I will ask him why it is written this way and update the post.  To me it seems a bit...redundant?  Surely there is a method to such methodical madness.  Anyway, you use baseUrl on all of the calls that can't be done locally and this code checks and returns the url to the SharePoint server instead.

So, here is the code:

var baseUrl = getBaseUrlforSharepointService();
function getBaseUrlforSharepointService() {
    try {
        var absUrl = window.location.href;
        var layoutsCharPosition =
            window.location.href.indexOf("SitePages") <= 0 ?
                (
                    window.location.href.indexOf("SitePages") <= 0 ?
                        (
                            window.location.href.indexOf("SitePages") <= 0 ?
                                window.location.href.indexOf("SitePages") :
                                window.location.href.indexOf("SitePages")
                        ) :
                        window.location.href.indexOf("SitePages")
                ) :
                window.location.href.indexOf("SitePages");
        var result = '';
        //check for the string "_layouts". Returns -1 if not found,else 
        //  returns the char position
        if (absUrl.indexOf("SitePages") >= 0 || absUrl.indexOf("SitePages") >= 0 ||
            absUrl.indexOf("SitePages") >= 0 || absUrl.indexOf("SitePages") >= 0)
        {
            result = absUrl.substr(0, layoutsCharPosition);
        }
        if (result.indexOf("localhost") === 7) {
            return "http://sharepoint.server.com/site";
        }
        return result;
    } catch (error) {
        alert("Could not Find Site Url")
    }
}

Keep coding!