如何从当前页面使用JavaScript获取主机的URL

鉴于我在以下页面:

http://www.webmail.com/pages/home.aspx 

如何使用JavaScript检索主机名称( "http://www.webmail.com" )?

 var host = window.location.hostname; 

或者可能

 var host = "http://"+window.location.hostname; 

或者如果你喜欢连接

 var protocol = location.protocol; var slashes = protocol.concat("//"); var host = slashes.concat(window.location.hostname); 

获取主机名: location.hostname

但是你的例子也在寻找这个scheme,所以location.origin似乎在Chrome中做了你想要的,但是在Mozdev文档中却没有提到。 你可以用它来构造它

 location.protocol + '//' + location.hostname 

如果你还想要端口号(当它不是80时),那么:

 location.protocol + '//' + location.host 

您可以使用以下命令获取协议,主机和端口:

 window.location.origin 

浏览器兼容性

桌面

 | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) | |----------------------------------|-------|-----------------|-------------------|-------|--------------------------------------------| | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | | 30.0.1599.101 (possibly earlier) | ? | 21.0 (21.0) | 11 | ? | 7 (possibly earlier, see webkit bug 46558) | 

移动

 | Android | Edge | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile | |----------------------------------|-------|------------------------|----------|--------------|--------------------------------------------| | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | | 30.0.1599.101 (possibly earlier) | ? | 21.0 (21.0) | ? | ? | 7 (possibly earlier, see webkit bug 46558) | 

所有浏览器兼容性来自Mozilla开发者networking

这应该工作:

 window.location.hostname 

我喜欢这个取决于目的

 window.location.href.split("/")[2] == "localhost:17000" //always domain + port 

您可以将其应用于任何urlstring

 var url = "http://localhost:17000/sub1/sub2/mypage.html?q=12"; url.split("/")[2] == "localhost:17000" url.split("/")[url.split("/").length-1] == "mypage.html?q=12" 

从url-string(相对path)中删除协议,域和path

 var arr = url.split("/"); if (arr.length>3) "/" + arr.splice(3, arr.length).join("/") == "/sub1/sub2/mypage.html?q=12"