简体   繁体   中英

How to get IFRAME to listen to same events as parent (and fire the same handlers)

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?

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM