Find an iframe that calls a function in the parent

I have several iframes on a page that shows users ads unicorns / bacon. Because it is not possible to detect the iframe domready event through the parent (please let me know if this is not the case) I have some initialization code in each iframe, like this:

<body data-controller="unicorn"> <!-- content --> <script> var $ = parent.jQuery; if($ && $.frameReady){ $(document).ready(function(){ $.frameReady(document); }); } </script> </body> 

parent document has code very similar to the following ( about this method via @Paul Irish):

 var frames = { // the following is irrelevant to my question but awesome. "unicorn": function (document) { var script = document.createElement("script"), element = document.getElementsByTagName("script")[0]; script.src = "http://www.cornify.com/js/cornify.js"; script.onload = function () { // defaultView is the DOMWindow. document.defaultView.cornify_add(); $(document).click(document.defaultView.cornify_add); script.parentNode.removeChild(script); }; element.parentNode.appendChild(script, element); }, "bacon" : function(document) { /** mmm, bacon **/ } }; // relevant but boring... $.frameReady = function(document){ var controller = $(document.body).data("controller"); controller && frames[controller] && frames[controller](document); }; 

Here is an example in jsfiddle ( you can edit it here ). It works fine (at least in Chrome dev).

Now I would like to get rid of the data-controller bit in the iframe and instead use the id (or data-* or something else) of the actual iframe element that is in the parent document to initialize the code.

If I could query the DOM via DOMWindow , it would look like this:

 $.frameReady = function(document){ var iframe = $("body").find(document.defaultView), controller = iframe.data("controller"); controller && frames[controller] && frames[controller](document); }; 

Fortunately, I only need this to work with web-based browsers, Adobe Air 2.5 (but I'm testing at a Chrome ATM).

Because S.O. defendants love this when the Question raises the question:

Are there (effective) ways to query the DOM via document or window in webkit-based browsers, including Adobe Air 2.5?

+4
source share
1 answer

Now I found that one iframe containing a unicorn is for you

 console.log( $("iframe").contents().filter( function(){ return this == document }).length ); 
+1
source

Source: https://habr.com/ru/post/1336474/


All Articles