56

They both seem to give me the same thing (the domain name currently executing the script).

So what's the difference (if any) and where should each be used?

2

1 Answer 1

89

MDN Web Docs - window.location

host....: the host name and port number. [www.google.com]:80
hostname: the host name (without the port number or square brackets). www.google.com

5
  • In my firebug console I get the same though - domain.com and domain.com. No square brackets, no port number. Here is the code: console.log(window.location.host); console.log(window.location.hostname); Jul 1, 2011 at 14:20
  • @Thomas it could be that the port is explicit only if it's non-standard (= not 80)
    – Pekka
    Jul 1, 2011 at 14:21
  • Fair enough. So, if I want the current domain name, its hostname. :) Many thanks - will accept as answer in 4 minutes! :p Jul 1, 2011 at 14:23
  • 1
    @Pekka In if you have example "localhost:80" which contains port 80, in that case "window.location.host" and "window.location.hostname" are same because 80 is default port. If you have "localhost:54198" you will have following results: window.location.host = "localhost:54198" and window.location.hostname = "localhost".
    – kat1330
    Nov 20, 2015 at 21:24
  • So then the difference between host & origin is that origin also has protocol attached?
    – Cody
    Dec 21, 2018 at 17:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.