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

Zac*_*ner 21 javascript base href

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

Zac*_*ner 37

这样做的正确方法是根据当前主机名执行标记的document.write:

正确:

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

此方法在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>
Run Code Online (Sandbox Code Playgroud)

  • 不应该`http:```document.location.protocol`? (6认同)
  • 没有理由说明为什么`document.write`将是"正确的"并且在文档树中正确插入节点将是"不正确的".问题属于"解决错误问题"的类别,但这里描述为"正确"的方法通常会在错误的地方插入"base"标签.如果代码在`head`部分,它是相当无用的(为什么不把正确的`base`标签放在那里作为普通的HTML?),如果它在其他地方执行,它通常会将`base`插入`body`. (5认同)
  • "不正确"的方法实际上并不起作用.让浏览器动态更改其基本href的唯一方法是"正确"方法. (3认同)
  • 嗨!根据我在启用角度的网页中的测试,document.write模式似乎没有添加基本标记,直到为时已晚.我在使用javascript添加标记或在标记中对其进行硬编码时比较了标记,看起来相同,但js解决方案不应用任何基本标记功能,即使"看起来"它已经到位......任何想法? (2认同)
  • 我发现在初始加载时,即使document.write高于样式表链接和其他资源,Chrome首先在原始URL上查找文件,然后再次使用<base />的内容重试.例如,如果我的原始URL是http://site.dev/account,并且document.write的结果是将基础设置为http://site.dev/,则资产首先尝试从/ account /加载,服务器返回404,然后从http://site.dev/正确加载. (2认同)

cod*_*kol 6

我不得不不同意最上面的答案。它不考虑协议,因此会失败。

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

    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);
Run Code Online (Sandbox Code Playgroud)

目前,这在包括 IE11 在内的所有主要浏览器中都运行良好

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

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

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


Mah*_*hir 5

我想你最好这样做

    <script type="text/javascript">
        document.head.innerHTML = document.head.innerHTML + "<base href='" + document.location.href + "' />";
    </script>
Run Code Online (Sandbox Code Playgroud)

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

  • 现在这实际上更合适(比使用`document.write`)。实际说明:这在 jsFiddle 中对我有用,而 `document.write` 没有。 (2认同)