15

I am calling the based url through javascript in a html page and I want to add the base url to call a link

eg.

<a href="getBaseURL()/filepath/index.html">Page</a>

The javascript is as follows:

function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));

    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

}

EDIT

Its just to get any base URL from the domain in question. Also, I got this code from a tutorial so any suggestions that will require less processing would be great thanks

SECOND EDIT

Hi All thanks for your answers so far, however, I am looking to call the function to the html tag as in <a href="getURL()/filepath/file.html></a>. This is where the problem lies, I am unsure how to do that

2
  • Do you have a question? Btw, localhost0 and localhost.foo.com are perfectly valid domains and not ones that are typically treated specially in /etc/hosts or other name resolution configurations, so your "http://localhost" === baseUrl.substring(0, 14) has an awful lot of hidden assumptions. You are also ignoring the effect of a <base href=>. Commented May 30, 2011 at 19:12
  • 1
    Could you provide an example URL and what baseURL could be than? I have the feeling you do a lot of unnecessary processing... Commented May 30, 2011 at 19:14

3 Answers 3

31
function getBaseURL () {
   return location.protocol + "//" + location.hostname + 
      (location.port && ":" + location.port) + "/";
}

Edit: Addressed Mike Samuel's point on nonstandard ports.

Sign up to request clarification or add additional context in comments.

8 Comments

If there is a path more than one directory level deep, a nonstandard port, or a <base href=...> element in the document then this is wrong.
@Mike Samuel: I'm not sure I understand what you mean by a path more than one directory level deep, but <base ...> and nonstandard ports for public sites are seldom used (in fact, I don't think I've ever seen the base tag in practice). He also stated that he wanted to "get the base URL from the domain question." If I were creating this function for a library, I would take into account all of the minutia involved. But since I'm not, I think I'll just use Occam's razor and assume he has the same configuration as 95% of sites on the Internet.
maybe your assertions about common environments are correct, but providing simplified code on a help forum without caveats is bad practice. If you know that it fails in certain situations mention that in the comments. Per directories, the base URL for http://example.com/foo/bar.html (absent an override from <base>) is http://example.com/foo/, not http://example.com/.
What about location.toString().replace(/\/$/, "")
@HorusKol: My statistics are based on common sense and experience. I'm not going to provide an exhaustive, rigorous proof for an off the cuff estimation. I'm not exactly sure where any of this is leading because nowhere did I claim my answer addressed 100% of the population. I took the heuristic approach and provided an answer for common case (which I determined using using experience-based statistics). If you think you can provide an answer that does, then donate your time to do so. I will gladly vote it up. Until then my contribution will have to do.
|
5

A general solution to allow for the use of <base> (or not) - a further improvement would be to have the baseDocument removed from the baseURL using some kind of regex.

function getBaseURL () {
    var baseURL = "";
    var baseDocument = "index.html";

    if (document.getElementsByTagName('base').length > 0) {
        baseURL = document.getElementsByTagName('base')[0].href.replace(baseDocument, "");
    } else {
        baseURL = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
    }

    return baseURL;
}

Comments

0

I am dealing with the same issue, and it isn't so much getting the base URL (as these answers have shown), but calling that javascript function from the element and then adding a relative path. Using @Christian Sanchez answer and other info I've found, this is an option using the onclick of the element:

JAVASCRIPT:

<script type="text/javascript">
    function getBaseURL(loc) {
        return location.protocol + "//" + location.hostname +
           (location.port && ":" + location.port) + "/" + loc;
    }
</script>

HTML:

<a href="filepath/index.html" onclick="getBaseURL(this.href);">TEST LINK</a>

Fiddle is here: http://jsfiddle.net/62g2bkyh/ (hover over link to see URL in fiddle - which shows base URL of iframe).

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.