4

I have several iframes on a page that display ads unicorns/bacon to users. Because its not possible to detect an iframe's domready event via the parent (please let me know if this isn't true) 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>

The parent document has code very similar to the following (about this technique 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 great (at least it does in Chrome dev).

Now what I would LIKE to do is get rid of the data-controller bit in the iframe and instead use the id (or data-* or whatever) 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);
};

Luckily, I only need this to run on webkit based browsers, Adobe Air 2.5 actually (but I'm testing in Chrome ATM).

Because S.O. answerers like it when a Question has a question here it is:

Is there any (efficient) ways to query the DOM via document or window in webkit-based browsers - including Adobe Air 2.5?

David Murdoch
  • 87,823
  • 39
  • 148
  • 191

1 Answers1

1

I have now found that one iframe containing the unicorn for you

console.log(
        $("iframe").contents().filter( function(){
           return this == document
        }).length
);
Bjorn Inge
  • 91
  • 3