How to get the host URL using JavaScript from the current page Ask Question

How to get the host URL using JavaScript from the current page Ask Question

Given that I'm on the following page:

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

How can I retrieve the host name ("http://www.webmail.com") with JavaScript?

ベストアンサー1

// will return the host name and port
var host = window.location.host; 

or possibly

var host = window.location.protocol + "//" + window.location.host;

or if you like concatenation

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;

If you have or expect custom ports use window.location.host instead of window.location.hostname

おすすめ記事