33

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

4

4 回答 4

42

这样做的正确方法是根据当前主机名对标签进行 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>
于 2010-08-16T16:04:00.493 回答
13

我认为你最好这样做

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

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

于 2017-06-11T01:21:37.077 回答
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 包,如果有人感兴趣,它还支持在这个基本 href 的末尾添加一个后缀

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

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

于 2019-09-12T15:51:50.400 回答
3
document.write("");

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

于 2016-08-26T04:29:04.290 回答