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

老子叫甜甜 提交于 2019-11-28 22:32:51

问题


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.


回答1:


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>



回答2:


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.




回答3:


document.write("");

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



回答4:


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



来源:https://stackoverflow.com/questions/3494954/how-do-i-set-a-pages-base-href-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!