0

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);
        }
anton980
  • 41
  • 1
  • 9

2 Answers2

2

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());
   });
Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
1

Pretty sure that the iframe contents have not been loaded yet, so the title cannot be fetched. Include an onload callback, and let that callback determine the name of the iframe AND THEN destroy the iframe and load the next.

Capture iframe load complete event

Community
  • 1
  • 1
Nate
  • 1,268
  • 13
  • 20