Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<iframe> javascript access parent DOM across domains?

I control the content of an iframe which is embedded in a page from another domain. Is there any way for javascript in my iframe to make changes to the parent's DOM?

For example, I would like to have my iframed script add a bunch of html elements to the parent DOM. This seems like a pretty tall order - thoughts?

Edit: There exists a technique called "Fragment ID Messaging" which might be a way to communicate between cross-domain iframes.

Edit: Also, Firefox 3.5, Opera, Chrome (etc) seem to be adopting the html5 "postMessage" api, which allows secure, cross-domain data transmission between frames, iframes and popups. It works like an event system. IE8 supports this feature, apparently, which is perhaps a little surprising.

Summary: No, you can't directly access/edit the DOM of a page from another domain. But you can communicate with it, and it can co-operate to make the changes you want.

like image 675
aaaidan Avatar asked Aug 18 '09 04:08

aaaidan


People also ask

Can an iframe access its parent dom?

If the content of the iframe and its parent have the same domain, you can access the parent pages DOM from the iframe by using parent. document.

What is cross domain iframes?

Learn about how cross-domain iframe can be used to safely circumvent browser restrictions on scripts that process code in a different domain. Applies to: Skype for Business 2015. Web applications that interact with UCWA 2.0 resources require a cross-domain iframe for all HTTP requests sent to UCWA 2.0.

How do you send iframe to postMessage?

postMessage in your web app sends to the main document's window , not to the iframe's. Specify the iframe's window object: document. getElementById('cross_domain_page').


2 Answers

Hate to say it but I'm like 99% sure that ain't happening directly because of security.

You can try it out here.

bhh

like image 86
Andy Gaskell Avatar answered Oct 17 '22 03:10

Andy Gaskell


It is possible.

You were right to mention postMessage in your edits. For those looking, there is a great backwards-compatible, javascript-only way to communicate across domains. Short, easy code as well. Perfect solution? As long as you can request modifications to the parent and the child:

http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage/

like image 11
Kyle Cureau Avatar answered Oct 17 '22 02:10

Kyle Cureau