Writing to a newly opened window in IE when the parent window specifies a document.domain
I’ve run into this problem before. IE considers a new window (or frame) opened with Javascript to be in a different domain than that of the window that opened it. Usually this won’t cause a problem, but if the parent window has document.domain explicitly set, then IE won’t allow the two windows to communicate with one another.
How I solved it before was to initially set the location on the new window to a dummy file on the same server as the parent window. This dummy file would be empty with the exception of a Javascript block that would set the document.domain.
However, this solution only works if you’re in control of the site loaded in the parent window.
My current project is a little more tricky. I’ve got a bookmarklet that creates the new window, and this bookmarklet can be clicked on while you’re visiting any site. The javascript in the bookmarklet is executed in the context of the page currently being viewed. The first thing my bookmarklet does is open a new window and then tries to write to it.
It wasn’t working on sites with document.domain set. I would get the dreaded “Access denied” error message.
I was pretty sure it was going to be impossible for me to get around this. I stumbled on a post on stackoverflow that gave me hope, though. Unfortunately, the posted solution didn’t work for me (though to be fair, the question never mentioned document.domain). However, it did give me an idea: set the window location to a Javascript URL that sets the document.domain. And thus here is my solution:
var w = window.open();
try {
w.document.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"
+ "<html><head></head><body>Test</body></html>");
w.document.close();
} catch(e) {
// If the first call fails because document.domain is set, try again with document.domain
w.location = "javascript:document.write('"
+ "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"
+ "<html><head><script type=\”text/javascript\”>document.domain=\”" + document.domain + “\”</script></head><body></body></html>’);document.close()”;
w.document.body.innerHTML = “Test”;
}