9

I want to assign a keydown event handler to an iframe. Something similar to the pure JS:

document.getElementById('iframe_id').contentWindow.addEventListener('keydown',funcName, true);

I tried:

$(document.getElementById('iframe_id').contentWindow).keydown( function() {
   // my func
});

But it does not work.. Please help!

ConroyP
  • 39,922
  • 16
  • 77
  • 86
  • possible duplicate of [keydown event on a iframe](http://stackoverflow.com/questions/1199075/keydown-event-on-a-iframe) – paulmorriss Oct 28 '13 at 15:17

4 Answers4

15

contentWindow is the iframe's window object. You want the iframe's document instead:

$(document.getElementById('iframe_id').contentWindow.document).keydown(function() {
    // my func
});

Note that I am not sure how jQuery reacts to elements from other windows/frames.

Crescent Fresh
  • 111,976
  • 25
  • 153
  • 138
  • 1
    Be wary with this. I believe this will cause a pretty large memory leak where the iframe's content will remain in memory even after you change its URL. – Josh Mouch Feb 14 '12 at 06:31
4

Just something to keep in mind: this will never work, as far as I understand, if the iframe content is cross-domain. You'll end up with permissions errors: Permission denied for http://... to get property HTMLDocument.nodeType from http://.... Browsers limit parent child dom permissions to same domain.

americanyak
  • 4,386
  • 3
  • 29
  • 34
0

This worked for me:

$('#iframe_id').contents().keydown(function() {
    // my func
});
Larry
  • 41
  • 2
0

The $ function replaces the need for document.getElementById

$('iframe_id').contentDocument.keydown(function() {
   // logic
});
Crescent Fresh
  • 111,976
  • 25
  • 153
  • 138
Mcbeev
  • 1,454
  • 8
  • 9