0

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?

4

2 回答 2

2

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.

于 2009-06-15T21:14:30.413 回答
0

事实证明,使用 iframe 元素的 contentDocument 属性从父 iframe 访问子 iframe 要容易得多,例如

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

    Element.observe($('id-of-iframe').contentDocument, "mousemove", function() {
      // call whatever...
    });
});
于 2009-06-16T01:57:11.387 回答