views:

3898

answers:

3

I have iframe on a page, the iframe and the parent page are in different domain, can a javascript code on the parent page access elements inside this iframe?

A: 

Yes, via the document.frames array you can access iframes.

changelog
it gave me this error: document.frames is undefined
Amr ElGarhy
You're ignoring the x-domain part of the question which is far more relevant. Also document.frames is non-standard, use window.frames which has wider support
annakata
-1 First of all, it's window.frames. Secondly, it still will not work if the pages are on different domains.
Josh Stodola
A: 

The easiest way would be through the frames object on window like this:

window.frames[0].document.getElementById('ElementId').style.backgroundColor="#000";
Richard
+5  A: 

It should not be able to if the pages are from different domains, the browsers security sandbox should prevent this type of access. It might work when the two pages are from different sub domains of the same domain, but that can and will differ between browsers (and possibly even versions of the same browser).

Accessing the child iframe might work, but the other way around will most certainly not work.

Gerco Dries
i am talking about access the child iframe elements, it should work?
Amr ElGarhy
only "might work" you'd have to tell us the domains to know
annakata
these are sites i am creating, and want them all to call one service.
Amr ElGarhy
You may be better off using an XMLHttpRequest object to call your service. All frames will then be able to access the service for themselves and they won't need any communication between them.
Gerco Dries