How to get base url with jquery or javascript?

JavascriptJquery

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

This one will help you...

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

Solution 2 - Javascript

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( '/' );

Solution 3 - Javascript

This will get base url

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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 + "' />";

Solution 6 - Javascript

the easiest way to get base url in JavaScript

window.location.origin

Solution 7 - Javascript

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;

Solution 8 - Javascript

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/

Solution 9 - Javascript

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

Solution 10 - Javascript

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.

Solution 11 - Javascript

You can easily get it with:

var currentUrl = window.location.href;

or, if you want the original URL, use:

var originalUrl = window.location.origin;

Solution 12 - Javascript

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.

Solution 13 - Javascript

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.

Solution 14 - Javascript

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

Solution 15 - Javascript

Here's a short one:

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

console.log(base);

Solution 16 - Javascript

window.location.origin+"/"+window.location.pathname.split('/')[1]+"/"+page+"/"+page+"_list.jsp"

almost same as Jenish answer but a little shorter.

Solution 17 - Javascript

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

Solution 18 - Javascript

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.

Solution 19 - Javascript

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+"://")]

Solution 20 - Javascript

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

Solution 21 - Javascript

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.

Solution 22 - Javascript

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;
    }

Solution 23 - Javascript

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

Solution 24 - Javascript

Split and join the URL:

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

Solution 25 - Javascript

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;
}
  }
}

Solution 26 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNavin RauniyarView Question on Stackoverflow
Solution 1 - JavascriptJenishView Answer on Stackoverflow
Solution 2 - JavascriptHaris N IView Answer on Stackoverflow
Solution 3 - JavascriptZaheer BabarView Answer on Stackoverflow
Solution 4 - JavascriptDaniil SamoylovView Answer on Stackoverflow
Solution 5 - JavascriptDustin HalsteadView Answer on Stackoverflow
Solution 6 - JavascriptQaisar MalikView Answer on Stackoverflow
Solution 7 - JavascriptArtjom B.View Answer on Stackoverflow
Solution 8 - JavascriptAKHIL KUMARView Answer on Stackoverflow
Solution 9 - JavascriptJohhnView Answer on Stackoverflow
Solution 10 - JavascriptBrian BolliView Answer on Stackoverflow
Solution 11 - JavascriptMohammad Jahidul AlamView Answer on Stackoverflow
Solution 12 - JavascriptAli SheikhpourView Answer on Stackoverflow
Solution 13 - JavascriptcagcakView Answer on Stackoverflow
Solution 14 - JavascriptMd. Khirul Islam OmiView Answer on Stackoverflow
Solution 15 - JavascriptmadebydavidView Answer on Stackoverflow
Solution 16 - JavascriptMateenView Answer on Stackoverflow
Solution 17 - JavascriptMarioView Answer on Stackoverflow
Solution 18 - JavascriptGrimView Answer on Stackoverflow
Solution 19 - JavascriptBlubbllView Answer on Stackoverflow
Solution 20 - JavascriptVikas ChaturvediView Answer on Stackoverflow
Solution 21 - JavascriptHexodusView Answer on Stackoverflow
Solution 22 - JavascriptnuanderView Answer on Stackoverflow
Solution 23 - JavascriptSyed Waqar HaiderView Answer on Stackoverflow
Solution 24 - Javascriptgrant sunView Answer on Stackoverflow
Solution 25 - JavascriptBa_Ro_NaView Answer on Stackoverflow
Solution 26 - JavascriptAsrofil Al BannaView Answer on Stackoverflow