鉴于我在下面这一页
http://www.webmail.com/pages/home.aspx
如何用JavaScript检索主机名(“http://www.webmail.com”)?
鉴于我在下面这一页
http://www.webmail.com/pages/home.aspx
如何用JavaScript检索主机名(“http://www.webmail.com”)?
当前回答
要获取主机名:location.hostname
但你的例子也在寻找方案,也就是位置。在Chrome中,origin似乎可以做你想做的事情,但在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开发者网络
我喜欢这个,取决于目的
window.location.href.split("/")[2] == "localhost:17000" //always domain + port
你可以在任何url字符串上应用它
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(相对路径)中删除协议,域和路径
var arr = url.split("/");
if (arr.length>3)
"/" + arr.splice(3, arr.length).join("/") == "/sub1/sub2/mypage.html?q=12"
要获取主机名:location.hostname
但你的例子也在寻找方案,也就是位置。在Chrome中,origin似乎可以做你想做的事情,但在Mozdev文档中却没有提及。你可以用
location.protocol + '//' + location.hostname
如果你也想要端口号(当它不是80时),那么:
location.protocol + '//' + location.host
let path = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port;
// will return the host name and port
var host = window.location.host;
或可能
var host = window.location.protocol + "//" + window.location.host;
或者如果你喜欢串联
var protocol = location.protocol;
var slashes = protocol.concat("//");
var host = slashes.concat(window.location.host);
// or as you probably should do
var host = location.protocol.concat("//").concat(window.location.host);
// the above is the same as origin, e.g. "https://stackoverflow.com"
var host = window.location.origin;
如果您有或期望自定义端口,请使用window.location.host而不是window.location.hostname