Search code examples
javascriptiframesrcprinting-web-page

Detect if all iframes in a page has src


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?


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
    }