views:

1164

answers:

2

I've got an HTML page (the parent) with an embedded IFRAME. The parent page has a couple of event listeners for mouse and keyboard events, as shown below (I'm using the Prototype library).

var IdleMonitor = Class.create({

    active: null,
    initialize: function(ii) {
        Element.observe(window, "mousemove", this.sendActiveSignal.bind(this));
    },

    sendActiveSignal: function() {
        console.log("MOUSE");
    }
});

var idleMonitor = new IdleMonitor();

The IFRAME, being a separate document and all, doesn't respond to the parent's events. So I've set up some code in the IFRAME like:

<script type="text/javascript" >

        Element.observe(window, "mousemove", function(p) {
      parent.sendActiveSignal();

     });
</script>

But that's giving me an error (sendActiveSignal is an undefined function). How do I make the IFRAME also listen for the same events and fire the parent's event handlers, preferably in a Prototype-y way?

+2  A: 

First of all, I really think you should use bindAsEventListener when binding functions as event listeners. By doing that, you have access to the event's arguments. You may need it later.

In your case, the first thing I noticed is that your sendActiveSignal is declared as a member of you IdleMonitor class. The JS engine won't find it if you just call it by parent.sendActiveSignal, since I'm guessing that parent is not a IdleMonitor instance. (And it is not, I can tell it right now :])

Inside your iframe, you have to access the idleMonitor variable, and you can do that by referencing it this way:

<script type="text/javascript">
Element.observe(window, "mousemove", function(p) { parent.document.idleMonitor.sendActiveSignal(); });
</script>

This pretty much should work, I can't test it right now.

wtaniguchi
Point taken on the bindAsEventListenter()... thanksHowever, the function is still undefined; must be because it's in that class?
yalestar
I will debug it when I get home, but if you are getting the idleMonitor member right (not a null instance or a undefined value), the problem probably lies on how prototype create classes(functions). I have done some work between frames and popup windows and they worked pretty fine... I had to implemented some 'magic' to make prototype'd objects to work tho.
wtaniguchi
On your answer about using contentDocument (I don't have 50 rep points yet, so I can't comment there), I wouldn't use it because:1. Cross-browsers issues: some IE versions don't handle it very well.2. This should be inside your iframe document, things will get messed up if you handle observers from the parent object.But hey... that's just me ;]
wtaniguchi
A: 

Turns out it's much easier to just access the child iframe from the parent using the contentDocument property of the iframe element, e.g.

document.observe("dom:loaded", function() {

    Element.observe($('id-of-iframe').contentDocument, "mousemove", function() {
      // call whatever...
    });
});
yalestar