Ad

Extracting Title From Multiple Iframes Inside A Div

- 1 answer

I've been fighting with this for a few days and cant seem to resolve the issue. I have several htmls (all reside in the same domain) that I load into a div inside a parent page as iframes. Then I try to extract a title from each of those iframes and push them into an array and then remove the iframes. Everything works great except the pageTitles array is populated with a number of blank strings. Thank you!

        var currentPage = 0;                
        var pages = new Array("page1.html", "page2.html", "page3.html", "page4.html");
        var maxPages = pages.length;    

        var pageTitles = [];

        for (i=0; i < maxPages; i++){
            var iframe = document.createElement('iframe');
            iframe.frameBorder=1;
            iframe.width = "400px";
            iframe.height = "50px";
            iframe.id="childFrame"+i;
            var frameTitle = iframe.id;
            iframe.setAttribute("src", pages[i]);
            document.getElementById("hidden").appendChild(iframe);
            //pageTitles.push(window.frames[i].document.title); // tried this with no luck
            pageTitles.push($("#"+frameTitle).contents().find("title").text());
            //pageTitles.push(document.getElementById(frameTitle)[0].document.title); // this is probably completely wrong, but thought I'd try it anyway
            document.getElementById("hidden").removeChild(iframe);
        }
Ad

Answer

You got to wait for the iframe to load. Only then you can fetch the content values. This might help.

$("#"+frameTitle).on('load',function(){
        pageTitles.push($(this).contents().find("title").text());
   });
Ad
source: stackoverflow.com
Ad