The base is dynamically set in php when an HTML page is built:
$base_line = '<base href="' . $some_path . '/" /> ';
echo $base_line;
Now that I am in the HTML page I need to access this information ($some_path) and after searching for a few hours I don't seem to find an answer. Please note that the loaded HTML page has a URL that is not related to the base and I don't have access to the PHP code to modify it. The loaded page could have a URL like: http://xyz.com/index.php, but all other links in the page will be based on the value set by the base so I can't get the base using the page URL.
I suppose I could grab one of the elements like an image and dissect it using DOM to find the base, but there should be an easier way to do this. Any ideas?
Using window.location doesn't work in this situation as it will return what is related to the loaded page URL and not what has been set as base within it.
Update 3
As @jorgecasar mentioned in his answer below, there is now a property, baseURI
on every Node
(which includes every Element
).
Calling document.baseURI
will get you the base path to the page, taking into account the <base>
tag.
Note that it is a recent-ish property that is supported by all modern browsers, but if you are using older browsers you might either want to stick with the older answers or make sure you have a poly- or ponyfill for it (Babel's standard polyfill seems to include one, though I couldn't find specific documentation saying as much).
Also, note that document.baseURI
will give you a fully-qualified absolute path, whereas getting the href
attribute from <base>
will give you the exact value you provided, so there may be a slight difference in the usage of the two.
Original
If you want to get the value of the base element, you can do something like:
var baseHref = document.getElementsByTagName('base')[0].href
Or to be a little safer:
var bases = document.getElementsByTagName('base');
var baseHref = null;
if (bases.length > 0) {
baseHref = bases[0].href;
}
Update: a more concise way would be:
const baseHref = (document.getElementsByTagName('base')[0] || {}).href;
baseHref
may be null if it doesn't have a <base>
.
Update 2: Instead of using getElementsByTagName()
, use querySelector()
:
var base = (document.querySelector('base') || {}).href;
console.log(base);
<base href="http://www.google.com"/>