Hemanth's Scribes

javascript

Get iframe contents using queryselectors

Author Photo

Hemanth HM

Thumbnail

With few security issues and hassles iframes have still managed to survive, the main reasons being:

  • iframes help to beat the same origin policy and implement the cross domain origin policy.
  • iframes allow multiple types of resources not just certain mime-types.

Maybe sandbox, srcdoc and seamless will help many, also the postMessage API!

But this article is not about explaining the good, bad and ugly of iframe, but it’s about selecting data from iframes!

Using document.frames['frame'] or window.frames['frame'] to get the frame, and then using the .innerHTML is absolutely wrong!

Rather something like document.getElementById('frame').contentWindow.document.body.innerHTML is perfectly fine!

But the fun is with doing the same with queryselectors!

I’m a big fan of queryselectors and have been pawing at it doing things like:

And this time I got some time to play with iframes, so using queryselectors this is how one can get the contents of an iframe:

Say you need the attributes of all the iframes that are present in the current page!

[].forEach.call(document.querySelectorAll('iframe'), function fn(elem) { 
    console.log(elem.attributes);
});

Getting the HTML data from an iframe on the same lines…

[].forEach.call(document.querySelectorAll('iframe'), function fn(elem) { 
    console.log(elem.contentWindow.document.body.innerHTML);
});

Querying specific content in an iframe:

[].forEach.call(document.querySelectorAll('iframe'), function fn(elem) { 
    console.log(elem.contentWindow.document.body.querySelectorAll('a'));
});

Hope you shall explore more on this, enjoy the raw power of JavaScript and happy hacking! :)

#javascript
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.