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 mea
<script>
document.write("<base href='"+ window.location.protocol +'//' + window.location.host + "' >");
</script>
I think you'd better do it this way
<script type="text/javascript">
document.head.innerHTML = document.head.innerHTML + "<base href='" + document.location.href + "' />";
</script>
As location.hostname does not return the application context root! You could also log the document.location on the console console.log to see all available metadata on document.location.
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>
I have to disagree with the top answer. The only reason the "Incorrect" solution is wrong is that is does not account for the protocol so it will fail.
A working solution that I have to account for protocol / host / port is the following
var base = document.createElement('base');
base.href = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
document.getElementsByTagName('head')[0].appendChild(base);
This currently works fine in all major browsers including IE11
I have used this to make an npm package that also supports adding a suffix to the end of this base href if anyone is interested
https://www.npmjs.com/package/dynamic-base
https://github.com/codymikol/dynamic-base