0

Edit:I'have solved the problem. You can check my comment below.

I want to get html elements of all iframes. These iframes can be located in my main page or they can be nested iframes. I want to get all iframes elements. There are many example on the internet to get elements of a specific iframe by id. For example; Get element value inside iframe which is nested inside Frame in javascript?

But i dont want to specify main iframe id or anything like this. I want to reach all iframes.(nested or not nested) I am very pleased if you can help me. Thank you.

I also have an example but it can reach only top iframe on the page with specific id. Here is my example;

var htmlDocument = document_root;
var numberOfFrame = $("iframe[id^='" + rules.frameId + "']").length;
if (numberOfFrame > 0) {
    htmlDocument = $("iframe[id^='" + rules.frameId + "']")[numberOfFrame - 1].contentDocument;
    formName = $("iframe[id^='" + rules.frameId + "']")[numberOfFrame - 1].id;
    var iframeList = [];
    iframeHTMLObjectList.push(htmlDocument);
    for (i = 0; i < htmlDocument.getElementsByTagName("iframe").length; i++) {
        iframeList.push(htmlDocument.getElementsByTagName("iframe")[i]);
    }
    for (i = 0; i < iframeList.length; i++) {
        iframeHTMLObjectList.push(iframeList[i].contentWindow.document);
    }
    console.log(formName);
}
can
  • 11
  • 6
  • 2
    Unless all these iframes are from same origin as main page you can't access them – charlietfl Aug 12 '18 at 15:38
  • For example; my main page has 2 iframes. These 2 iframes also have 3 iframes.So i want to get html elements of these 8 iframes.(2 main, 6 nested). Is there any way to access them? I guess it must be. – can Aug 12 '18 at 15:55
  • If they are on same domain need to let each frame page load then access internal frames. If not same domain can't access them – charlietfl Aug 12 '18 at 16:52

1 Answers1

1

I've solved the problem with recursive method. Here is my method:

function getIframeElements(htmlDocument) {
var frames = htmlDocument.getElementsByTagName("iframe");
if (frames.length > 0) {
    for (var i = 0; i < frames.length; i++) {
        try {
            formName = frames[i].id;
            getIframeElements(frames[i].contentWindow.document);
        } catch (err) {
            console.log(err);
        }

    }
}

if (!iFrameArr.includes(htmlDocument)) {
    iFrameArr.push(htmlDocument);
}

return iFrameArr;

}

can
  • 11
  • 6