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.
I guess you will run to security problems without using a proxy. Proxies can be very to use. You can try one of those:
(1) a PHP based proxy (be careful cause there are a lot of ads between useful links)
(2) a Apache .htaccess proxy - just create a subdirectory
proxy
in your domain and put there a.htaccess
file containing:Put the other domain name in place of picasaweb.google.com
Personally I prefer using the Apache proxy
For AJAX, the server could return the header
Access-Control-Allow-Origin: *
to allow cross-domain access. Maybe it works also for IFRAMEs.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/
Yes you can.
You can implement window.postMessage to communicate accross iframes and/or windows across domains.
But you need to do it in an asynchronous way.
If you need it synchronously, you need to implement wrappers around those asynchronous methods.
Child.htm
Here, you would modify the child to send postmessages to parent. e.g. in child.htm, you do
and in parent, you do (in receiveMessage)
eval(evt.data);
Not that using eval is insecure, so you would instead pass an enum, and call the corresponding function that you need to put on the parent page.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