1

Is it possible to loop and display nested iframes one by one in javaScript?
for instance:

<iframe id="iframe1" style="border: 0; position: absolute; display: none; width: 100%; height: 100%; left: 0; top: 0">
    <p>iframe 1</p>
    <iframe id="iframe2" style="border: 0; position: absolute; display: none; width: 100%; height: 100%; left: 0; top: 0">
        <p>iframe 2</p>
        <iframe id="iframe3" style="border: 0; position: absolute; display: none; width: 100%; height: 100%; left: 0; top: 0">
            <p>iframe 3</p>
        </iframe>
    </iframe>
</iframe>

1 Answers1

0

Well i can just say, explicitly if you dont need it to work this way (you can change the enviroment) change it!

for everyone else theres this little piece of code (well its bad but it works):

/* ty to -> https://stackoverflow.com/questions/1452871/how-can-i-access-iframe-elements-with-javascript */
function iframeRef( frameRef ) {
 return frameRef.contentWindow ? frameRef.contentWindow.document : frameRef.contentDocument;
}

/* loop through frames and iframes, starts default at top */
function frameLooper(cb, rec = 0, base = top.document) {
 return base.querySelectorAll('iframe:not(.hiddenFrame), frame:not(.hiddenFrame)').forEach(function(el, index){
  var doc = iframeRef(el);
  /* empty body -> gtfo */
  if (!doc.body || !doc.body.children.length){
   return true;
  }
  /* execute callback with -> iframe.document */
  typeof cb == 'function' && cb(doc);
  /* recursive callback */
  rec && frameLooper(cb, rec, doc);
 });
}

just go with your callback function as executable, you're getting the iframe document as parameter. And if you want to use this for nested frames too, set the second param to something truthy.

so as an example you may just start with

top.frameLooper(function(e){console.log(e);}, 1);

Edit: forgott to mention that if you want the frame to get exluded add the class "hiddenFrame" to the iframe / frame.

Dxg125
  • 51
  • 1
  • 7