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

JavaScript HTML

Stafan

2020-03-23

与检查用户代理是否通过正确的域进行访问相比,以下哪一项最有效?

如果他们使用某种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说主机包含端口。

应该验证一下location.host/hostname还是在IE6 +中以及我们将要存在的所有其他内容中完全确定?

第2899篇《location.host与location.hostname和跨浏览器的兼容性?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
樱小胖Mandy 2020.03.23

互动链接解剖

作为一个小提示:交互式链接剖析

-

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

  • hostname 给你 example.org
  • host 给你 example.org:8888
阿飞 2020.03.23

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

您真正想要的是:

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

如果指定了端口号,则主机仅包含端口号。如果URL中没有专门的端口号,则它返回与主机名相同的端口号。您可以选择是否要匹配端口号。有关更多信息,请参见https://developer.mozilla.org/en/window.location

我假设您希望主机名仅获取站点名称。

村村小卤蛋 2020.03.23

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

It seems that you will get the same result for both, but hostname contains clear host name without brackets or port number.

猴子村村 2020.03.23

Just to add a note that Google Chrome browser has origin attribute for the location. which gives you the entire domain from protocol to the port number as shown in the below screenshot. chrome开发人员工具

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android