Get iframe contents using queryselectors

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

  • iframes helps to beat the same origin policy and implements the cross domain origin policy.

  • iframes allows multiple types of resources not just certain mime-types.

May be  sandbox, srcdoc and  seamless will help many, also postMessage API!

But this article is not about explaining the good, bad and ugly of iframe, but its 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 some like document.getElementById('frame').contentWindow.document.body.innerHTML; is perfectly fine!

But the fun is with doing the same with queryselectors!

/me is a big fan of queryselectors and have been pawing at it doing things like :

And this time it 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 is 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! :)

Share this