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

2022-08-30 00:50:05

鉴于我在以下页面上:

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

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


答案 1
// 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


答案 2

获取主机名:location.hostname

但是您的示例也在寻找该方案,因此似乎在Chrome中执行了您想要的操作,但在Mozdev文档中却未提及。您可以使用以下命令构建它location.origin

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

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

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