如何在 Javascript 中设置页面的基本 href?

问题描述 投票:0回答:5

我想根据当前主机名在 Javascript 中设置页面的基本 href 属性。我已经生成了可以在不同主机名上查看的 HTML 页面,这意味着生成一个基本 href 标记将在一个主机名下工作,但在另一个主机名下将不正确。

javascript href radix
5个回答
44
投票

正确的做法是根据当前主机名对标签进行 document.write:

正确:

<script type="text/javascript">
document.write("<base href='http://" + document.location.host + "' />");
</script>

此方法在IE、FF、Chrome、Safari中都得到了正确的结果。它会产生(正确的)与执行以下操作不同的结果:

错误:

<script type="text/javascript">
var newBase = document.createElement("base");
newBase.setAttribute("href", document.location.hostname);
document.getElementsByTagName("head")[0].appendChild(newBase);
</script>

13
投票

我认为你最好这样做

    <script type="text/javascript">
        document.head.innerHTML = document.head.innerHTML + "<base href='" + document.location.href + "' />";
    </script>

因为

location.hostname
不返回应用程序上下文根!您还可以在控制台
document.location
上记录
console.log
以查看
document.location
上的所有可用元数据。


4
投票

我不同意最佳答案。它不考虑协议,所以它会失败。

我必须考虑协议/主机/端口的工作解决方案如下

    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);

这在包括 IE11 在内的所有主要浏览器中都可以正常工作

我已经用它制作了一个 npm 包,如果有人感兴趣的话,它还支持在这个 base href 的末尾添加一个后缀

https://www.npmjs.com/package/dynamic-base

https://github.com/codymikol/dynamic-base


2
投票
文档.write("");

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


0
投票
window.document.head.innerHTML=`<base href=${href}>`+window.document.head.innerHTML;

href变量就是你要使用的href。

© www.soinside.com 2019 - 2024. All rights reserved.