1

I am trying to get the site base url using javascript . I am using

var pathArray = window.location.pathname.split( '/' );
var baseURL = window.location.protocol + "//" + window.location.host + "/" + pathArray[1]+'/';

This is working for mysite.com/project1 but not for mysite.com.

How can I check this for both the urls ? I have to send ajax request to the url.

Thanks in advance.

empiric
  • 7,825
  • 7
  • 37
  • 48
tarangini
  • 67
  • 6
  • Please remove the PHP tag, this question has fundamentally nothing to do with PHP. – Eujinks Nov 24 '14 at 08:51
  • possible duplicate of [Get current URL in JavaScript?](http://stackoverflow.com/questions/406192/get-current-url-in-javascript) – IROEGBU Nov 24 '14 at 08:59

4 Answers4

1

This one should work (depending on your definition of "base URL"):

<script>
 /**
 * Get the parts of an URL.
 *
 * @param url URL to fetch information from
 * @return parts of an URL
 */
function getURLParts(url) {
    var parser = document.createElement('a');
    parser.href = url;
    return parser;
}

// Show the URL information
var parser = getBaseURL(window.location);
alert(parser.protocol);
alert(parser.host);
alert(parser.hostname);
alert(parser.port);
alert(parser.pathname);
alert(parser.hash);
alert(parser.search);
</script>
www.data-blogger.com
  • 4,076
  • 7
  • 43
  • 65
0

simply use the location property of window e.g. window.location.href

<script>
  alert(window.location.href);
</script>
amd
  • 20,637
  • 6
  • 49
  • 67
0

I guess you need the base URL of the current Website. From this answer:

pathArray = window.location.href.split( '/' );
protocol = pathArray[0];
host = pathArray[2];
url = protocol + '//' + host;
Community
  • 1
  • 1
Crunch
  • 107
  • 2
  • 19
0

Base URL should be defined in a special tag in header:

<head>
<base href="http://example.com/project1/">
</head>

Then you can read it with Javascript: in modern browsers

var baseURL = document.baseURI

or in older

var baseURL = document.getElementsByTagName('base')[0].href
KIlya
  • 141
  • 3