31

What is the difference between using location.hostname and document.domain?

I think an explanation with an example would be helpful.

Andreas
  • 2,045
  • 5
  • 19
  • 30

1 Answers1

17

It seems that document.domain is a read only property, except in Mozilla, which lets you change the value of the domain that is used for the same origin policy of (for example) AJAX requests without actually updating the page.

The restrictions on this are the same rules of the Same Origin Policy.

At least this is my understanding of the MDC docs for document.domain.

From the docs:

Gets/sets the domain portion of the origin of the current document, as used by the same origin policy.

...

In the DOM HTML specification, this property is listed as being read-only. However, Mozilla will let you set it to a superdomain of the current value, constrained by its base domain. For example, on developer.mozilla.org it is possible to set it to "mozilla.org" but not "mozilla.com" or "org".

Try updating document.domain and window.location.hostname to a new value in the console, and see the difference.

Community
  • 1
  • 1
user113716
  • 318,772
  • 63
  • 451
  • 440
  • Seems that it is useful in Safari/Chrome/Firefox (haven't tested in IE or Opera yet). You can basically reduce a sub-domain to one of its super-domains (except for the TLD) for purposes affected by Same Origin Policy. It does not change the location of the page itself. – user113716 Nov 19 '10 at 15:36
  • That's exactly what it's for. It's only useful when you change it. – Tim Down Nov 19 '10 at 15:51
  • @Tim: This one was new to me. Do you happen to know off hand if it is well supported in IE as a non ready-only property? Otherwise, I'll fire up VMWare in a bit and test it. – user113716 Nov 19 '10 at 15:57
  • Yes, it's supported non-read-only in IE, since version 4 I think. – Tim Down Nov 19 '10 at 16:10
  • @Tim - Thanks much! Saved me the trouble. Much appreciated. – user113716 Nov 19 '10 at 16:46