admin管理员组

文章数量:1410682

In my application, I have an iframe and I would like to give it access to some functionality which changes the state of the application outside the iframe. This functionality must be triggered by a keydown event either inside or outside the iframe.

In the iframe, I have the following code:

window.init = function (api) {
    api.bind(document);
};

And the outer application does something like:

iframe.contentWindow.init({
    bind: function (element) {
        $(element).bind('keydown', function () {
            debugger;
        });
    }
});

With this, init is called properly, but the keydown event handler is never called. What am I doing wrong?

In my application, I have an iframe and I would like to give it access to some functionality which changes the state of the application outside the iframe. This functionality must be triggered by a keydown event either inside or outside the iframe.

In the iframe, I have the following code:

window.init = function (api) {
    api.bind(document);
};

And the outer application does something like:

iframe.contentWindow.init({
    bind: function (element) {
        $(element).bind('keydown', function () {
            debugger;
        });
    }
});

With this, init is called properly, but the keydown event handler is never called. What am I doing wrong?

Share edited Jul 17, 2022 at 7:45 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Nov 17, 2010 at 20:19 stragerstrager 90.1k27 gold badges138 silver badges180 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

If you try to bind event in this way:

    $(element).bind('keydown', function () {
        alert("hello");
    });

jquery will try to traverse your element in parent window, but if you do the following your problem would be solved:

    $(iframe.contentWindow.document.body).find(element).bind('keydown', function () {
        alert("hello");
    }); 

The problem is that some part of the iframe has already attached a keydown handler which stops propagation of the event, preventing the event from reaching the document and preventing the handler from being called. Nothing was wrong with the actual binding.

本文标签: javascriptAttach event to iframe element in parent codeStack Overflow