首页 文章

location.host与location.hostname和跨浏览器的兼容性?

提问于
浏览
299

在检查用户代理是否通过正确的域访问时,哪一项最有效 .

如果他们使用某种Web代理访问域名(因为它往往会打破js),我们希望显示一个基于小js的“顶栏”样式警告 .

我们考虑使用以下内容:

var r = /.*domain\.com$/;
if (r.test(location.hostname)) {
    // showMessage ...
}

这将照顾我们曾经使用的任何子域 .

我们应该使用哪个主机名或主机名?

在Firefox 5和Chrome 12中:

console.log(location.host);
console.log(location.hostname);

..两者显示相同 .

是因为端口实际上不在地址栏中吗?

W3Schools表示主机包含端口 .

Should location.host/hostname be validated or can we be pretty certain in IE6+ and all the others it will exist?

6 回答

  • 68

    MDN:https://developer.mozilla.org/en/DOM/window.location

    看起来两者都会得到相同的结果,但 hostname 包含没有括号或端口号的明确主机名 .

  • 3

    只需添加一条说明Google Chrome浏览器具有该位置的原始属性 . 它为您提供从协议到端口号的整个域,如下面的屏幕截图所示 .
    chrome developers tool

  • 868

    interactive link anatomy

    作为一个小备忘录:interactive link anatomy

    简而言之(假设 http://example.org:8888/foo/bar#bang 的位置):

    • hostname 给你 example.org

    • host 给你 example.org:8888

  • 27

    如果有指定的端口号,则主机只包含端口号 . 如果URL中没有专门的端口号,则返回与hostname相同的端口号 . 您选择是否要匹配端口号 . 有关详细信息,请参阅https://developer.mozilla.org/en/window.location .

    我想你想要主机名来获取网站名称 .

  • 0

    如果您坚持使用 window.location.origin 在阅读 origin 之前,您可以将其放在代码顶部

    if (!window.location.origin) {
      window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
    }
    

    Solution

    PS:为了记录,它实际上是原始问题 . 他们可能已经编辑过了 . :)

  • 9

    您的主要问题已在上面得到解答 . 我只是想指出你正在使用的正则表达式有一个错误 . 它也将成功 foo-domain.com ,这不是 domain.com 的子域

    你真正想要的是这个:

    /(^|\.)domain\.com$/
    

相关问题