views:

205

answers:

3

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 ff 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?

+2  A: 

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).

Justin Johnson
Thanks alot, Justin. Can you (or someone else) provide a link about events not bubbling up from an iframe?
allyourcode
From [the specs](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-bubbling): "propagation will continue up to and including the Document." It is important to understand that an iframe has an own document element. Again, citing [the specs](http://www.w3.org/TR/REC-html40/struct/objects.html#idx-document): "the embedded document remains independent of the main document"
Pumbaa80
Specifications are rarely the same as implementations :(
Justin Johnson
+1  A: 

rather then catch an event on the main page, you can catch the event at the iframe, and call a function on the main page.

<-- main page -->
function catchIt()
{
 // code here
}


<-- iframe page -->

function doIt()
{
 top.catchIt(); 
}

<a onclick="doIt();">test</a>

i think it would work but didnt test it

TeKapa
Don't you mean parent.catchIt, not top.catchIt?
allyourcode
when you have frames inside other frames, top means the parent os all frames.
TeKapa
+1  A: 

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'); });
dsldsl
Ah. I think the key here is that you used parent.document. The difference is that parent is a Window object vs. parent.document is an Element. Thanks!
allyourcode