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

前端 未结 4 1231
清歌不尽
清歌不尽 2020-12-25 11:48

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

相关标签:
4条回答
  • 2020-12-25 12:21
    document.write("");

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

    0 讨论(0)
  • 2020-12-25 12:30

    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.

    0 讨论(0)
  • 2020-12-25 12:32

    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>
    
    0 讨论(0)
  • 2020-12-25 12:39

    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

    0 讨论(0)
提交回复
热议问题