QuerySelector for Web Elements Inside iframe

后端 未结 3 1200
不思量自难忘°
不思量自难忘° 2020-12-05 10:08

Edit: New title. What I\'m looking for is a document.querySelector for elements inside an iframe.

I\'ve done quite a bit of Googling for an answer and finally I\'m s

相关标签:
3条回答
  • 2020-12-05 10:23

    simple es6 adapted from h3manth:

    document.querySelectorAll('iframe').forEach( item =>
        console.log(item.contentWindow.document.body.querySelectorAll('a'))
    )
    
    0 讨论(0)
  • 2020-12-05 10:23

    Here's a snippet for diving into same-origin frames (ie-compatible ES5):

    function findInFramesRec(selector, doc) {
      var hit = doc.querySelector(selector);
      if (hit) return hit;
      var frames = Array.prototype.slice.call(doc.frames);
      for(var i = 0; (i < frames.length) &&   !hit   ; i++) {
        try {
          if (!frames[i] || !frames[i].document) continue;
          hit = findInFramesRec(selector, frames[i].document);
        } catch(e) {}
      }
      return hit;
    }
    

    This dives into both frameset frames and iframes alike. It may even survive (though not enter) cross origin frames.

    0 讨论(0)
  • 2020-12-05 10:27

    if the original page's url isn't at the same domain with the iframe content, the javascript will treat the iframe as a black box, meaning it will not see anything inside it.

    0 讨论(0)
提交回复
热议问题