Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can events fired from an iframe be handled by elements in its parent?

Suppose I have a page located at www.example.com/foo, and it contains an <iframe> with src="http://www.example.com/bar". I want to be able to fire an event from /bar and have it be heard by /foo. Using the Prototype library, I've tried doing the following without success:

Element.fire(parent, 'ns:frob');

When I do this, in Firefox 3.5, I get the following error:

Node cannot be used in a document other than the one in which it was created" code: "4 Line 0

Not sure if that's related to my problem. Is there some security mechanism that's preventing scripts in /bar from kicking off events in /foo?

like image 473
allyourcode Avatar asked Jan 12 '10 04:01

allyourcode


People also ask

Can parents communicate with iframe?

Yes, it's not any hack or something, but with simple functions you can communicate in between iframe and it's parent website. First of all, let's know about the iframe. 'iframe' is very popular html tag which enables you to keep another webpage inside a webpage.

How do I transfer data from iframe to parent?

Sending data from child iframe to parent window : Whenever you embed an iframe, the iframe will have a reference to the parent window. You just need to use the PostMessage API to send data via the window. parent reference of the parent window.

Can I get element inside iframe?

To get the element in an iframe, first we need access the <iframe> element inside the JavaScript using the document. getElementById() method by passing iframe id as an argument. const iframe = document.

Are iframes considered bad practice?

Iframes Bring Security Risks. If you create an iframe, your site becomes vulnerable to cross-site attacks. You may get a submittable malicious web form, phishing your users' personal data. A malicious user can run a plug-in.


2 Answers

Events can be handled by a function defined the parent window if the iframe is a page from the same domain (see MDC's article on Same Origin Policy); however, events will not bubble up from the iframe to the parent page (at least not in my tests).

like image 100
Justin Johnson Avatar answered Oct 10 '22 19:10

Justin Johnson


I haven't tested this cross-browser yet, but it works in FF.

In the iFrame you can fire on the element parent.document:

Event.observe(window, 'load', function() {
  parent.document.fire('custom:event');
});

and in the parent frame you can catch it with:

document.observe('custom:event', function(event) { alert('gotcha'); });
like image 41
dsldsl Avatar answered Oct 10 '22 17:10

dsldsl