how to get the host url using javascript from the current page

后端 未结 7 1903
猫巷女王i
猫巷女王i 2020-12-22 17:20

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.

7条回答
  •  自闭症患者
    2020-12-22 17:40

    // 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

提交回复
热议问题