我希望能够通过JavaScript基于当前主机名设置页面的base href属性。我生成的HTML页面可以在不同的主机名上查看,这意味着生成base href标签将在一个主机名上工作,但在另一个主机名上将不正确。
我希望能够通过JavaScript基于当前主机名设置页面的base href属性。我生成的HTML页面可以在不同的主机名上查看,这意味着生成base href标签将在一个主机名上工作,但在另一个主机名上将不正确。
正确的方法是根据当前主机名使用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>
document.write
是“正确”的,而将节点正确插入文档树则是“错误”的。这个问题属于“解决错误问题”的范畴,但这里描述的方法通常会在错误的位置插入base
标签。如果代码位于head
部分,这样做是无用的(为什么不像普通HTML一样放置正确的base
标签?),而如果在其他位置执行,则通常会将base
插入到body
中。 - Jukka K. Korpela我认为你最好这样做。
<script type="text/javascript">
document.head.innerHTML = document.head.innerHTML + "<base href='" + document.location.href + "' />";
</script>
location.hostname
无法返回应用程序上下文根!您还可以在控制台上使用console.log
记录document.location
,以查看有关document.location
的所有可用元数据。
document.write
)。实际上,就实用性而言:在 jsFiddle 中,这种方式对我有效,而 document.write
则无效。 - YakovL我不同意前面的答案。因为它没有考虑到协议,所以会失败。
我提供了一个可行的解决方案来考虑协议/主机名/端口,具体如下:
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的末尾添加后缀。
<script>
document.write("<base href='"+ window.location.protocol +'//' + window.location.host + "' >");
</script>
$.serverRoot
为主机的相对根目录(例如$.serverRoot = '/myapp/';
),并将其包含在内。 - Bob Fincheimer