281

In joomla php there I can use $this->baseurl to get the base path, but I wanted to get the base path in jquery.

The base path may be any of the following example:

http://www.example.com/
http://localhost/example
http://www.example.com/sub/example

The example may also change.

4
  • possible duplicate of How to get the base path in jQuery? Commented Aug 8, 2014 at 12:06
  • 1
    @Mritunjay I already saw that, but in my case the base path is different as I wished to get the base path like in php we do in joomla Commented Aug 8, 2014 at 12:07
  • So, none of the answers solved your problem? Commented Aug 13, 2014 at 17:51
  • pick an answer, please? Commented Nov 14, 2017 at 15:40

25 Answers 25

313

I think this will work well for you:

var base_url = window.location.origin;

var host = window.location.host;

var pathArray = window.location.pathname.split( '/' );

Here is the Can I Use... table

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

6 Comments

window.location.origin is not defined in ie9
@jnoreiga Who's still using ie9 ツ
I wish it were that simple @AlexandreDaubricourt
These do not work between localhost and a published solution.
what does this show in an iframe?
|
238

This one will help you...

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

3 Comments

Yes, it works! http://localhost/myapp/what/ever/sub/folder -> getBaseUrl -> http://localhost/myapp :-)
This won't work in all the cases, as indicated by somehow undervoted answer by @Artjom B. For example, when a site is tested over local network (and domain is substituted with IP + local path) the base url could be something like 192.168.0.23/~sites/site/html/ instead of site.dev. Getting the full pathname with Javascript is not an option too, because a site can have any number of virtual subdirectories.
best answer...works fine for me in ionic and react.js
42

This will get base url

var baseurl = window.location.origin+window.location.pathname;

2 Comments

this is the same as window.location.href
it is not the same, pathname gives you the path segment of the url, href contains the query params as well
42

document.baseURI returns base URL also respecting the value in <base/> tag https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI

3 Comments

This also returns the hashbang, which most probably not what the OP wanted
@Marcel That is NOT an issue so long as you set the <base> tag in the head of the document. This is the BEST answer on this page!
Fun fact: if <base> is not defined in DOM the baseURI will return current URI. At least in chrome
27

This is an extremely old question, but here are the approaches I personally use ...

Get Standard/Base URL

As many have already stated, this works for most situations.

var url = window.location.origin;


Get Absolute Base URL

However, this simple approach can be used to strip off any port numbers.

var url = "http://" + location.host.split(":")[0];

Edit: To address the concern, posed by Jason Rice, the following can be used to automatically insert the correct protocol type ...

var url = window.location.protocol + "//" + location.host.split(":")[0];


Set Base URL

As a bonus -- the base URL can then be redefined globally.

document.head.innerHTML = document.head.innerHTML + "<base href='" + url + "' />";

1 Comment

Unless your protocol is something other than http like https (then setting the url protocol to "http://" will present some really weird errors depending on how you want to use the url).
14

This is not possible from javascript, because this is a server-side property. Javascript on the client cannot know where joomla is installed. The best option is to somehow include the value of $this->baseurl into the page javascript and then use this value (phpBaseUrl).

You can then build the url like this:

var loc = window.location;
var baseUrl = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "") + "/" + phpBaseUrl;

2 Comments

Note that loc.host has the port, for an url like http://localhost:8082/ this method will produce http://localhost:8082:8082/, window.location.hostname should be used instead.
@TiberiuC. Thanks, added.
9
var getUrl = window.location;
var baseurl = getUrl.origin; //or
var baseurl =  getUrl.origin + '/' +getUrl.pathname.split('/')[1]; 

But you can't say that the baseurl() of CodeIgniter(or php joomla) will return the same value, as it is possible to change the baseurl in the .htaccess file of these frameworks.

For example :

If you have an .htaccess file like this in your localhost :

RewriteEngine on
RewriteBase /CodeIgniter/
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

The $this->baseurl() will return http://localhost/CodeIgniter/

Comments

8

Had the same issue a while ago, my problem was, I simply needed the base url. There are a lot of detailed options here but to get around this, simply use the window.location object. Actually type this in the browser console and hit enter to select your options there. Well for my case it was simply:

window.location.origin

Comments

5

I've run into this need on several Joomla project. The simplest way I've found to address is to add a hidden input field to my template:

<input type="hidden" id="baseurl" name="baseurl" value="<?php echo $this->baseurl; ?>" />

When I need the value in JavaScript:

var baseurl = document.getElementById('baseurl').value;

Not as fancy as using pure JavaScript but simple and gets the job done.

Comments

5

Here's a short one:

const base = new URL('/', location.href).href;

console.log(base);

Comments

5

You can easily get it with:

var currentUrl = window.location.href;

or, if you want the original URL, use:

var originalUrl = window.location.origin;

1 Comment

What's the difference?
4

The format is hostname/pathname/search

So the url is :

var url = window.location.hostname + window.location.pathname + window.location.hash

For your case

window.location.hostname = "stackoverflow.com"
window.location.pathname ="/questions/25203124/how-to-get-base-url-with-jquery-or-javascript"
window.location.hash = ""

So basically the baseurl = hostname = window.location.hostname

Comments

4

I am surprised that non of the answers consider the base url if it was set in <base> tag. All current answers try to get the host name or server name or first part of address. This is the complete logic which also considers the <base> tag (which may refer to another domain or protocol):

function getBaseURL(){
  var elem=document.getElementsByTagName("base")[0];
  if (typeof(elem) != 'undefined' && elem != null){
     return elem.href;
  }
  return window.location.origin;
}

Jquery format:

function getBaseURL(){
  if ($("base").length){
     return $("base").attr("href");
  }
  return window.location.origin;
}

Without getting involved with the logic above, the shorthand solution which considers both <base> tag and window.location.origin:

Js:

var a=document.createElement("a");
a.href=".";
var baseURL= a.href;

Jquery:

var baseURL= $('<a href=".">')[0].href

Final note: for a local file in your computer (not on a host) the window.location.origin only returns the file:// but the sorthand solution above returns the complete correct path.

3 Comments

This is not the best way. Also, see @DaniilSamoylov's answer, which does incorporate the <base> element.
baseURI returns the base URL of a node so in this case it returns the base path + document name. you will need more codes to remove the document name from that URL. @Brad
This solution does not give back the correct base URL when the root directory of the web page is within a sub directory (e.g. example.com/appRoot). It only works when the root dir of the webpage is directly located on the webhost's root.
3

I would recommend for everyone to create HTML base tag in development, then assign the href dynamically, so in production whatever host a client uses, it will automacically addapt to it:

<html>
 <title>Some page title</titile>
  <script type="text/javascript">
    var head  = document.getElementsByTagName('head')[0];
    var base = document.createElement("base");
    base.href = window.document.location.origin;
    head.appendChild(base);
  </script>
 </head>
 ...

So if you are in localhot:8080, you will reach every linked or referenced file from the base, eg: http://localhost:8080/some/path/file.html If you are in www.example.com, it will be http://www.example.com/some/path/file.html

Also note that, every location you're on, you should not use references like globs in hrefs, eg: Parent location causes http://localhost:8080/ not http://localhost:8080/some/path/.

Pretent you reference all hyperlinks as full sentenced without the bas url.

Comments

3

A simpler answer is here, window.location.href = window.location.origin;

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.
2
window.location.origin+"/"+window.location.pathname.split('/')[1]+"/"+page+"/"+page+"_list.jsp"

almost same as Jenish answer but a little shorter.

Comments

2

I was just on the same stage and this solution works for me

In the view

<?php
    $document = JFactory::getDocument();

    $document->addScriptDeclaration('var base = \''.JURI::base().'\'');
    $document->addScript('components/com_name/js/filter.js');
?>

In js file you access base as a variable for example in your scenario:

console.log(base) // will print
// http://www.example.com/
// http://localhost/example
// http://www.example.com/sub/example

I do not remember where I take this information to give credit, if I find it I will edit the answer

Comments

1

You mentioned that the example.com may change so I suspect that actually you need the base url just to be able to use relative path notation for your scripts. In this particular case there is no need to use scripting - instead add the base tag to your header:

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

I usually generate the link via PHP.

Comments

1

Easy

$('<img src=>')[0].src

Generates a img with empty src-name forces the browser to calculate the base-url by itself, no matter if you have /index.html or anything else.

4 Comments

This seems the most elegant solution of all and the only one that doesn't duplicate browser logic, which is nice. I do wonder how portable it is. Is there anything in the HTML specs that would suggest this is guaranteed to work in all browsers?
@MatthijsKooijman Depends on interpretation of html specs. If you say a filename of length 0 is a valid resource-name ... it does match all browsers.
Understand how browsers are made. You have a couple of programmers, the (indirect) wish to built a browser. Their first source is the html-specs. They read the specs and this is one of the questions they realy like to solve. How would you think they (all) decide on this circumstances?
This should be the selected answer.
1
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];

1 Comment

Please consider adding a description to your answer.
1

Here's something quick that also works with file:// URLs.

I came up with this one-liner:

[((1!=location.href.split(location.href.split("/").pop())[0].length?location.href.split(location.href.split("/").pop())[0]:(location.protocol,location.protocol+"//" + location.host+"/"))).replace(location.protocol+"//"+location.protocol+"//"+location.protocol+"://")]

Comments

0

In case anyone would like to see this broken out into a very robust function

    function getBaseURL() {
        var loc = window.location;
        var baseURL = loc.protocol + "//" + loc.hostname;
        if (typeof loc.port !== "undefined" && loc.port !== "") baseURL += ":" + loc.port;
        // strip leading /
        var pathname = loc.pathname;
        if (pathname.length > 0 && pathname.substr(0,1) === "/") pathname = pathname.substr(1, pathname.length - 1);
        var pathParts = pathname.split("/");
        if (pathParts.length > 0) {
            for (var i = 0; i < pathParts.length; i++) {
                if (pathParts[i] !== "") baseURL += "/" + pathParts[i];
            }
        }
        return baseURL;
    }

2 Comments

This just gives the whole url. Not a base URL.
indeed, not sure where I was going with that. I have long since switched to setting that with server-side code
-1

Split and join the URL:

const s = 'http://free-proxy.cz/en/abc'
console.log(s.split('/').slice(0,3).join('/'))

Comments

-2

Getting the base url |Calls controller from js

function getURL() {

var windowurl = window.location.href;
var baseUrl = windowurl.split('://')[1].split('/')[0]; //split function

var xhr = new XMLHttpRequest();
var url='http://'+baseUrl+'/url from controller';
xhr.open("GET", url);
xhr.send(); //object use to send

xhr.onreadystatechange=function() {
    if(xhr.readyState==4 && this.status==200){
 //console.log(xhr.responseText); //the response of the request
        
 document.getElementById("id from where you called the function").innerHTML = xhr.responseText;
}
  }
}

Comments

-5

Put this in your header, so it will be available whenever you need it.

var base_url = "<?php echo base_url();?>";

You will get http://localhost:81/your-path-file or http://localhost/your-path-file.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.