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)
我不得不不同意最上面的答案。它不考虑协议,因此会失败。
我必须考虑协议/主机/端口的工作解决方案如下
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
我想你最好这样做
<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
.