Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can javascript access iframe elements from the parent page?

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?

like image 801
Amr Elgarhy Avatar asked Apr 08 '09 11:04

Amr Elgarhy


People also ask

Can JS access iframe?

Apart from accessing an element by adding its control to the Controls Repository, there is also the possibility to access an element within a web page's iframe via Javascript.

How can an iframe communicate with its parent?

All you have to do is first dispatch an event from the iframe to the parent that notifies the parent that the iframe is loaded (essentially a "ready message"). The parent will be listening for messages and if it receives the "ready message" event, it can then reply to the iframe with whatever message you want to send.

Can an iframe access its parent?

window); When a page is running inside of an iframe, the parent object is different than the window object. You can still access parent from within an iframe even though you can't access anything useful on it.


2 Answers

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.

like image 73
Gerco Dries Avatar answered Sep 21 '22 07:09

Gerco Dries


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

window.frames[0].document.getElementById('ElementId').style.backgroundColor="#000";
like image 27
Richard Avatar answered Sep 23 '22 07:09

Richard