Question

I have a page with a dynamic number of iframes. window.print() has to be called when iframes has loaded (ie. has src).

How can this be handled elegantly in pure JavaScript without being to pedantic?

Was it helpful?

Solution

function getLoadedFrames () {

    var frames = document.getElementsByTagName( 'iframe' ), // Get all iframes
        loadedFrames = [], i;

    for ( i = 0; i < frames.length; i++ ) {
        /*
            If iframe has a src attribute, that attribute has a value AND
            that value is not equal to the current window location (leaving src
            blank seems to return the current location instead of empty string)
            then add the frame to the loadedFrames array.
        */
        if ( frames[ i ].src && frames[ i ].src.length > 0 && frames[ i ].src !== window.location.href ) {
            loadedFrames.push( frames[ i ] );
        }
    }

    return loadedFrames; // An array of your 'loaded' frames
}

OTHER TIPS

Not quite sure if that's what you want, but perhaps it helps:

window.addEventListener("DOMContentLoaded", function(){
    // Get all iframes as soon as DOM has loaded
    var iframes = document.getElementsByTagName("iframe");
    for (var i = 0, l = iframes.length; i < l; ++i) {
        // Add event handler to every iframe
        iframes[i].onload = function(){
            // Execute window.print() when iframe has loaded
            window.print();
        };
    }
});

This works without checking the src attribute, because if a iframe doesn't have a src, the onload event will never be fired.

Note that this won't work in IE; see this answer on SO for an equivalent to jQuery's $(document).ready...

You could do

function areAllIframesLoaded() {
  var frames = document.getElementsByTagName( 'iframe' )
  return Array.prototype.slice.call(frames).reduce(function(p, c) {
    return p && c.src && c.src.length > 0 && c.src !== window.location.href
  }, true);
}

This will iterate over all the iframes and return true or false on whether or not all of them have a src defined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top