简体   繁体   中英

detect a dynamically loaded iframe

I need to know when a specific iframe is created on a page. The iframe is created with JS when the user presses a button, and can be created and destroyed many times.

UPDATED: The JS that creates the iframe is part of the original page so I cannot modify it or access its variables or functions, chrome extensions are sandboxed.

I don't have control over the contents of the iframe and cannot inject any JS in it. I can only inject JS in the main page but have no other control on it otherwise.

(it's for a chrome extension and as far as I know it's only possible to inject JS code in the main page or iframes loaded with the page but not iframes created dynamically after the page has loaded)

For the moment I do this:

window.setInterval( function() {
  $("iframe").each(function(){
    if ($(this).attr('id')) {
      if ($(this).attr('id') == "iframe_id") {
        //my code
      }
    }
  });
}, 1000);

but I would really like to avoid the setInterval because of performance issues. Would this be possible at all somehow?

A. Wolff probably answered your question already ("The iframe is created with JS when the user presses a button" So you know when the iframe is created").

If you're still not sure what to do... well:

The interval is not a good idea - but you probably figured that out yourself. Try the on() method. That should help.

$( "iframe" ).on( "click", function() {
     alert( "This is my iframe!" );
});

If you are having trouble selecting the content of the iframe, maybe you should try accessing elements like this:

$( "#iframe-id" ).contents().find( ".what-i-am-looking-for" ).hide();

The jQuery documentation will be extremely helpful if that is what you are looking for:

http://api.jquery.com/on/

http://api.jquery.com/contents/

Cheers!

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