7

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?

Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301

7 Answers7

14

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
  • 6,682
  • 1
  • 26
  • 35
3

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

window.frames[0].document.getElementById('ElementId').style.backgroundColor="#000";
Richard
  • 21,728
  • 13
  • 62
  • 101
1

If the two domains are completely seperate then it is impossible

Lloyd Moore
  • 3,117
  • 1
  • 32
  • 32
1

Use jQuery.postMessage plugin http://benalman.com/code/projects/jquery-postmessage/docs/files/jquery-ba-postmessage-js.html

Browsers Tested Internet Explorer 6-8, Firefox 3, Safari 3-4, Chrome, Opera 9.

Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
0

You can use CORS to achieve this, specifically changing the 'document.domain' value to match in both parent & child. But, please undestand the security implications of this, and that you require access to the source code of both parent & child documents.

This is especially important if you own multiple sub domains. I use this technique all the time, so I know it works, even with SSL.

Charles Robertson
  • 1,760
  • 16
  • 21
0

It could be done with Chrome using --disable-web-security parameter... ;)

campino2k
  • 1,618
  • 1
  • 14
  • 25
-2

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

changelog
  • 4,646
  • 4
  • 35
  • 62
  • 1
    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 Apr 08 '09 at 11:38
  • 6
    -1 First of all, it's window.frames. Secondly, it still will not work if the pages are on different domains. – Josh Stodola Apr 09 '09 at 14:33