I want to set a page's base href attribute in Javascript based off of the current hostname. I have generated HTML pages that can be viewed on different hostnames, which means generating a base href tag will work in one hostname but will be incorrect in the other.
The <base> tag must have either an href or a target attribute present, or both. There can only be one single <base> element in a document, and it must be inside the <head> element.
The href attribute specifies the base URL for all relative URLs on a page.
The effect of the base tag is global to the document, and the only way to override the effect of <base href="..."> is to use absolute URLs. You can use window. location in JavaScript to get the URL of the page itself, in case the document was retrieved via HTTP. And you could use it to construct absolute URLs.
The HTML <base> tag is used to specify a base URI, or URL, for relative links. For example, you can set the base URL once at the top of your page in header section, then all subsequent relative links will use that URL as a starting point.
The correct way of doing this is to do a document.write of the tag based off the current hostname:
Correct:
<script type="text/javascript"> document.write("<base href='http://" + document.location.host + "' />"); </script>
This method has produced correct results in IE, FF, Chrome, and Safari. It produces a (correct) different result than doing the following:
Incorrect:
<script type="text/javascript"> var newBase = document.createElement("base"); newBase.setAttribute("href", document.location.hostname); document.getElementsByTagName("head")[0].appendChild(newBase); </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With