Ad

Can I Fetch A Title Of An External Page In My Domain Using JavaScript?

- 1 answer

I have several pages (all reside in the same directory as master page) that are loaded into the parent via iFrame. I would like to fetch each one of the child pages titles and load them into an array. Is that possible?

Best I could do so far is to pass the tile from a child page when the page is loaded into an iFrame, but I need to preload all the titles from the start in order to populate the table of contents as shown below:

Parent code:

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

function pageTitle(title){   //called from inside a child HTML
    document.getElementById("titleText").innerHTML = title;
};

child code:

window.onload = function passTitle(){
    var title = $(document).find("title").text();
    parent.pageTitle(title);
};
Ad

Answer

You want to use window.frames - this is a list of frame objects (not an array - important to know for the second solution)

Then, the simplest way is this

var pageTitles = [];
for (i = 0; i < window.frames.length; i++) {
    if( !!window.frames[i].document) { // only frames in same domain
        pageTitles.push(window.frames[i].document.title);
    }
}

Or, little more advanced, but in my opinion the nicer way

var pageTitles = [].filter.call(window.frames, function(frame) {
    return !!frame.document; // return only frames in same domain
}).map(function(frame) {
    return frame.document.title;
});

actually you could use just window without the .frames - at least in firefox, because window.frames === window - however, I'd recommend using window.frames for clarity in code

Ad
source: stackoverflow.com
Ad