tarangini
tarangini

Reputation: 67

How o get site URL on server using javascript

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.

Upvotes: 1

Views: 1313

Answers (4)

KIlya
KIlya

Reputation: 141

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

Upvotes: 0

www.data-blogger.com
www.data-blogger.com

Reputation: 4164

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>

Upvotes: 1

Crunch
Crunch

Reputation: 109

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;

Upvotes: 0

amd
amd

Reputation: 21502

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

<script>
  alert(window.location.href);
</script>

Upvotes: 0

Related Questions