How do I set a page's base href in Javascript?

Viewed 49712

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.

4 Answers

I have to disagree with the top answer. It 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

Related