views:

1978

answers:

3

Is there a way to access the DOM of the document in an iframe from parent doc if the doc in the iframe is on another domain? I can easily access it if both parent and child pages are on the same domain, but I need to be able to do that when they are on different domains.

If not, maybe there is some other way to READ the contents of an iframe (one consideration was to create an ActiveX control, since this would be for internal corporate use only, but I would prefer it to be cross-browser compatible)?

+3  A: 

Not really. This is essential for security – otherwise you could open my online banking site or webmail and mess with it.

You can loosen restriction a bit by setting document.domain, but still top level domain must be the same.

You can work around this limitation by proxying requests via your own server (but don't forget to secure it, otherwise s[cp]ammers may abuse it)

my.example.com/proxy?url=otherdomain.com/page
porneL
+1  A: 

Theoretically you can access the the content of the iframe using the standard DOM level2 contentDocument property. Practically you may have found out that most browsers deny the access to the DOM of the external document due to security concerns. Access to the full DOM AFAIK is not possible (though there might be some browser-specific tweak to disable the same-domain check); for cross-domain XHR a popular trick is to bounce the data back and forth the iframe and the main document using URL fragment identifiers (see e.g. this link), you can use the same technique but:

  • the document loaded in the iframe must cooperate, and
  • you don't have access to the full document anyway (you can read back some parameters, or maybe you can try and URL-encode the whole document - but that would be very ugly)
Luca Tettamanti
A: 

I just found postMessage method introduced with HTML5; it's already implemented in recent browser (FF3, IE8 and Safari 4). It allows the exchange of messages between any windows object inside the browser. For the details see the documentation at MDC and this nice tutorial by John Resig.

Luca Tettamanti