Observe events in iframe

471 views
Skip to first unread message

AlannY

unread,
Jun 24, 2008, 8:52:28 AM6/24/08
to Prototype: Core
Is it possible to observe events in iframe?

var iframe = new Element('iframe');

iframe.observe('mouseup', function (e) { ... }); // Not works ;-(

I found that in FF, I can

iframe.contentWindow.document.addEventListener('mouseup', function (e)
{...}, true); // Works

But, how to do it with Prototype?
tnx

artemy tregoubenko

unread,
Jun 24, 2008, 9:33:23 AM6/24/08
to prototy...@googlegroups.com
Prototype shortcuts are tailored to work in current window. However you
can use generic prototype methods like this:

Event.observe(iframe.contentWindow.document, 'mouseup', function (e){})

--
arty ( http://arty.name )

tancurrom

unread,
Jun 25, 2008, 3:01:56 PM6/25/08
to Prototype: Core
You got me thinking and playing around with prototype. Elaborating on
what arty said, it is not actually possible to extend element in
frames because prototype makes reference to the window object when
extending elements. It would take a big rewrite to let it accept an
object and make reference to it instead of the window and document
directly each time.

I played about and this might help some what.... (IE doesn't like the
script)

Element.addMethods('iframe', {
document: function(element) { //this isn't the best?
element = $(element);
if (element.contentWindow)
return element.contentWindow.document;
else if (element.contentDocument)
return element.contentDocument;
else
return null;
},
$: function(element, frameElement) { //well neither is this really
xD
element = $(element);
var frameDocument = element.document();
if (arguments.length > 2) {
for (var i = 1, frameElements = [], length = arguments.length; i
< length; i++)
frameElements.push(element.$(arguments[i]));
return frameElements;
}
if (Object.isString(frameElement))
frameElement = frameDocument.getElementById(frameElement);
return frameElement || element;
}
});

Example....
var iframe = $('iframe');
var iframeElement = iframe.$('iframeElement');
Event.observe(iframeElement, 'mouseup', function(){
console.log('yup');
});
Event.observe($('iframe').$('iframeElement'), 'mouseup', function(){
console.log('yup2');
});

Or what you were looking for....
Event.observe($('iframe').document(), 'mouseup', function(){
console.log('yup3');
});

Note....
$('iframe').$('iframeElement').update('some text'); // -> error (no
method) [Element.extend is cannot be called on the iframe element
before it is returned]
Reply all
Reply to author
Forward
0 new messages