What does document.domain = document.domain do?

mjs picture mjs · Sep 26, 2009 · Viewed 82.7k times · Source

The client-side JS component of Orbited (a Comet server), requires that if the server is running on a different domain or port to the JS itself, you must execute

document.domain = document.domain;

before any other JS is loaded. (See the documentation.)

What does this do? It looks like a NOOP! (I've checked and it is in fact necessary.)

Answer

Michael Carter picture Michael Carter · Oct 6, 2009

I actually wrote this code.

When trying to do cross-subdomain/port comet, the iframe needs to have the same document.domain value as the parent frame. Unfortunately, the browser stores the domain name AND port internally for the original document.domain value. But the getter and setter in javascript knows nothing about the port. So the problem is this: if the top frame document.domain is ('example.com', 80), and the bottom frame is ('comet.example.com', 80), how do you get the bottom frame to be ('example.com', 80) as well?

You can't, as changing the hostname portion will necessarily cause the port to be set to null, so the best you can do is ('example.com', null) in the bottom frame. So the top frame also needs to be set to that value, and setting document.domain=document.domain does just that. It changes the internal representation in the browser from ('example.com', 80) to ('example.com', null) and then everything matches up and cross-port/subdomain frame communication works.