开发者

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

开发者 https://www.devze.com 2023-01-11 14:45 出处:网络
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 hos开发者_C百科tnames, which means generating a

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 hos开发者_C百科tnames, which means generating a base href tag will work in one hostname but will be incorrect in the other.


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 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.


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


document.write("");

<script>
document.write("<base href='"+ window.location.protocol +'//' + window.location.host + "' >");
</script>

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号