Monday, September 19, 2011

Javascript: Recursively Fetch All Documents Associated With Frames

A recursive Javascript function to get all objects of type HTMLDocument from all iframes in a document and all their children.  It might need some refinement.  For example, there is an HTMLDocument associated with iframe, when all you might want are the documents associated with the frames.


//Returns array including current document and all documents in all frames
function getAllDocuments()
{
documents = [document];
childDocuments = getAllChildDocuments(documents);
return documents.concat(childDocuments);
}

//Recursive function drills down into all iframe and frame documents
// docs: array of HTMLDocument types
function getAllChildDocuments(docs)
{
childDocuments = []
var docsLength = docs.length;
for (var docIndex = 0; docIndex < docsLength; docIndex++)
{
var iframes = docs[docIndex].getElementsByTagName("iframe")
var iframesLength = iframes.length;
if (iframesLength > 0)
{
for (var iframeIndex = 0; iframeIndex < iframesLength; iframeIndex++)
{
var iframeDocument = iframes[iframeIndex].contentDocument;
if (iframeDocument)
{
childDocuments.push(iframeDocument);
var frames = iframeDocument.getElementsByTagName("frame");
var framesLength = frames.length;
if (framesLength > 0)
{
for (frameIndex = 0; frameIndex < framesLength; frameIndex++)
{
var frameDocument = frames[frameIndex].contentDocument;
if(frameDocument)
{
childDocuments.push(frameDocument);
}
}
}
}
}
}
}
if(childDocuments.length > 0)
{
return childDocuments.concat(getAllChildDocuments(childDocuments));
}
return childDocuments;
}

No comments:

Post a Comment