0

I want to bind an event on some iframes that are dynamically created on a page.

There is a way to bind events on regular elements that don't exist yet on page, using jQuery's .on() method, and passing a selector as second parameter. Like this :

$(document).on('click', 'div', () => { 
  // some code 
});

But iframe behaves differently I guess. This won't work:

$(document).on('click', 'iframe', () => { 
  // some code 
});

Also I thought of these:

$(window).on('click', 'document', () => {});
// or
$(document).on('click', 'body', () => {});

None of them worked.

Also I thought of another approach:

$(document).on('load', 'iframe', e => {
  $(e.target).contents().find('body').on('click', () => {
    // some code
  });
});

Didn't even bind the load event for iframes.

I MIGHT be able to handle it with completely different approach. I can bind the click event else where in code, each time an iframe is created, and they are infact "existed" in the page, then I might be able to bind any event I want to them. But I want to do that as the last solution. If there is a way to bind these events on page load for any iframes that will be created dynamically in the page, please suggest a solution.

UPDATE: I am on the same-domain, so the cross-origin restrictions don't apply.

arm
  • 82
  • 1
  • 15
  • Listening for click events in an iframe *at all* doesn't really work, though you can check when the window gets blurred and see if the new active element is the iframe (first click only) – CertainPerformance Jul 28 '19 at 07:11
  • 1
    $('iframe').contents().find('body').click(() => { }); – arm Jul 28 '19 at 07:45
  • @CertainPerformance The code above, binds a click event on an iframe successfully and it works perfectly. – arm Jul 28 '19 at 07:46
  • @CertainPerformance Also I don't understand why you closed this thread as duplicate when the link you provided is clearly about something different. I already know how to bind events on iframe. I just want to know how to do it dynamically. When the iframe doesn't exist yet and I cannot select it using regular methods. Wasn't my explanations clear enough? – arm Jul 28 '19 at 07:49
  • Oh, you're on the same-domain, so the cross-origin restrictions don't apply, sorry about that. Events inside an iframe don't bubble out of it, so I *think* you'll have to attach a listener when the iframe is created, since event delegation on the top window doesn't work. The iframe could also use `postMessage` that the top level listens for. – CertainPerformance Jul 28 '19 at 07:51

0 Answers0