简体   繁体   中英

add `load` event for EVERY iFrame on a page

I have a page that has dynamically added iFrames in it. I want to catch the "onLoad" event for every iFrame.

So basically, I want to attach the event to the body but have it apply to every child iFrame. This works for other events, but it seems like the "load" event isn't propagating.

Here's what I've tried so far:

 $(document).on("load", "iframe", function() { $("body").append("this is what I want, but it doesn't work!"); }); var iFrame = $("<iframe/>", { srcdoc : "<html style='overflow: hidden;'><body>Appended iFrame</body></html>" }); $("body").append(iFrame); iFrame.on("load",function(){ $("body").append("this seems to work.... but isn't what I'm looking for."); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

and here it is on jsfiddle: https://jsfiddle.net/skeets23/qsrf802z/8/

Any way to get this working as expected? So I can just create one binding and have it work for any number of dynamically added iFrames?

Seems you want to add iframe dynamically, so, best method is catch event DOMNodeInserted of document. See example follow:

 $(document).on('DOMNodeInserted', function(e) { //check is iframe is loaded if(e.target.localName=="iframe"){ console.log("New iframe loaded!"); $("div").append("this does NOT seem to work!"); }; }); function addIframe(){ var iFrame = $("<iframe />", { srcdoc : "<html style='overflow: hidden;'><body>Appended iFrame</body></html>" }); $("body").append(iFrame); iFrame.on("load",function(){ $("div").append("this seems to work...."); }); }; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button onclick="addIframe();">Add Iframe</button> <div> </div> 

Change $(document).on("load" ... to $("iframe").on("load", ... . And place it at end of script, it will work!

 var iFrame = $("<iframe />", { srcdoc : "<html style='overflow: hidden;'><body>Appended iFrame</body></html>" }); $("body").append(iFrame); iFrame.on("load",function(){ $("div").append("this seems to work...."); //alert("cde"); }); $("iframe").on("load", function () { $("div").append("this does NOT seem to work!"); alert("abc"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> </div> 

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