Get The Current Domain Name With Javascript (Not the path, etc.)

前端 未结 17 2256
情歌与酒
情歌与酒 2020-12-04 05:43

I plan on buying two domain names for the same site. Depending on which domain is used I plan on providing slightly different data on the page. Is there a way for me to de

17条回答
  •  醉酒成梦
    2020-12-04 06:15

    You can get it from location object in Javascript easily:

    For example URL of this page is:

    http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc
    

    Then we can get the exact domain with following properties of location object:

    location.host = "www.stackoverflow.com"
    location.protocol= "http:"
    

    you can make the full domain with:

    location.protocol + "//" + location.host
    

    Which in this example returns http://www.stackoverflow.com

    I addition of this we can get full URL and also the path with other properties of location object:

    location.href= "http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"    
    location.pathname= "questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"
    

提交回复
热议问题