Created
April 7, 2015 12:43
-
-
Save ivan-demchenko/33288f1bb0b0b42c8078 to your computer and use it in GitHub Desktop.
Get the content of an iFrame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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