0

Trying to use helpful code provided at using document.getElementsByTagName on a page with iFrames - elements inside the iframe are not being picked up but both samples seem to look into first "level" of iframes and not inside of iframes inside other iframes.

Tried:

const subtreeSet = (root, theset) => {
    if (!theset) theset=new Set();
    if (!root || theset.has(root)) return theset;
    theset.add(root);
    if (root.shadowRoot) {
        Array.from(root.shadowRoot.children).forEach(child => subtreeSet(child, theset));
    } else {
        if (root.tagName === 'IFRAME') { try { root=root.contentDocument.body; theset.add(root); } catch (err) { root=null; /* CORS */ } }
        if (root && root.getElementsByTagName) for (const child of root.getElementsByTagName('a')) subtreeSet(child, theset);
    }
    return theset;
}

console.log(subtreeSet(document));

expected to see all links, but saw only ones not inside nested iframes.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Sergiy
  • 1

1 Answers1

0

the iframe in HTML is a little bit special tag. To you access to this tag you have 2 options contentWindow or contentDocument. You have the information in this link Stack OverFlow question.

After, you can check this other link to know how to combine these 2 properties. The code should be something like this:

var iframe = document.getElementById('iframeId');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var innerTag = innerDoc.getElementsByTagName('a');

Remember that in your code you are doing root.contentDocument.body, this .body is not correct.