Skip to content

Instantly share code, notes, and snippets.

@ivan-demchenko
Created April 7, 2015 12:43
Show Gist options
  • Save ivan-demchenko/33288f1bb0b0b42c8078 to your computer and use it in GitHub Desktop.
Save ivan-demchenko/33288f1bb0b0b42c8078 to your computer and use it in GitHub Desktop.
Get the content of an iFrame
// Sometimes it's needed to get access to body or head elements within an iFrame.
// Here is a peace of code that helps to do this without jQuery.
var iFrameContent = window.iFrameContent || {};
iFrameContent.withIn = function(iFrameElement) {
if (!iFrameElement) {
throw 'Please, specify an iFrame to work with';
}
if (iFrameElement.nodeName !== 'IFRAME') {
throw 'iFrame element is expected';
}
var doc = iFrameElement.contentWindow || iFrameElement.contentDocument;
return {
getHead: function() {
return doc.document ? doc.document.head : null;
},
getBody: function() {
return doc.document ? doc.document.body : null;
}
}
};
// Usage
// <iframe id="myWindow"></iframe>
var iFrameElem = document.querySelector('#myWindow');
var iFrameBody = iFrameContent.withIn(iFrameElem).getBody();
if (iFrameBody) {
// do stuff
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment