261

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.

Navin Rauniyar
  • 10,127
  • 14
  • 45
  • 68

26 Answers26

279

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( '/' );
Srdjan Pazin
  • 103
  • 2
  • 5
Haris N I
  • 6,474
  • 6
  • 29
  • 35
235

This one will help you...

var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
Jenish
  • 2,383
  • 1
  • 10
  • 4
  • 1
    Yes, it works! `http://localhost/myapp/what/ever/sub/folder` -> getBaseUrl -> `http://localhost/myapp` :-) – vee Jul 29 '16 at 09:23
  • 6
    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. – certainlyakey Aug 01 '16 at 09:49
  • 1
    best answer...works fine for me in ionic and react.js – Betini O. Heleno Sep 07 '20 at 17:05
42

This will get base url

var baseurl = window.location.origin+window.location.pathname;
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Zaheer Babar
  • 1,636
  • 1
  • 15
  • 17
37

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

Daniil Samoylov
  • 489
  • 4
  • 5
  • This also returns the hashbang, which most probably not what the OP wanted – Marcel Jan 22 '20 at 16:24
  • 1
    @Marcel That is NOT an issue so long as you set the tag in the head of the document. This is the BEST answer on this page! – Jieiku Aug 07 '22 at 19:24
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 + "' />";
Dustin Halstead
  • 741
  • 6
  • 19
  • 1
    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). – Jason Rice Nov 04 '19 at 23:39
23

the easiest way to get base url in JavaScript

window.location.origin
mesqueeb
  • 5,277
  • 5
  • 44
  • 77
Qaisar Malik
  • 439
  • 3
  • 6
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;
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
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/

AKHIL KUMAR
  • 123
  • 1
  • 5
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
Johhn
  • 979
  • 17
  • 24
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.

Brian Bolli
  • 1,873
  • 1
  • 12
  • 14
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;
kmoser
  • 8,780
  • 3
  • 24
  • 40
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

Arif
  • 6,094
  • 4
  • 49
  • 81
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.

Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82
  • 1
    This is not the best way. Also, see @DaniilSamoylov's answer, which does incorporate the `` element. – Brad Dec 09 '19 at 03:43
  • 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 – Ali Sheikhpour Dec 09 '19 at 06:04
  • 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. http://www.example.com/appRoot/). It only works when the root dir of the webpage is directly located on the webhost's root. – John Ranger Apr 08 '20 at 02:31
4

Here's a short one:

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

console.log(base);
madebydavid
  • 6,457
  • 2
  • 21
  • 29
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.

cagcak
  • 3,894
  • 2
  • 21
  • 22
2
window.location.origin+"/"+window.location.pathname.split('/')[1]+"/"+page+"/"+page+"_list.jsp"

almost same as Jenish answer but a little shorter.

Mateen
  • 1,631
  • 1
  • 23
  • 27
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

Mario
  • 4,784
  • 3
  • 34
  • 50
2

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

  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jan 10 '22 at 19:08
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.

Grim
  • 1,938
  • 10
  • 56
  • 123
  • 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? – Matthijs Kooijman Jan 13 '19 at 13:06
  • @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. – Grim Jan 13 '19 at 18:17
  • 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? – Grim Jan 13 '19 at 18:20
  • 1
    This should be the selected answer. – norcal johnny Aug 09 '20 at 02:28
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+"://")]
Pang
  • 9,564
  • 146
  • 81
  • 122
Blubbll
  • 17
  • 4
1
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
0

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.

Hexodus
  • 12,361
  • 6
  • 53
  • 72
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;
    }
nuander
  • 1,319
  • 1
  • 19
  • 33
-1

Split and join the URL:

const s = 'http://free-proxy.cz/en/abc'
console.log(s.split('/').slice(0,3).join('/'))
jkdev
  • 11,360
  • 15
  • 54
  • 77
grant sun
  • 120
  • 5
-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;
}
  }
}
-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.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38