Skip to content

Instantly share code, notes, and snippets.

@omidnasri
Forked from monjer/jQuery.iframe.js
Created October 13, 2016 18:28
Show Gist options
  • Save omidnasri/e7a9f75e01d181955c4391b43566c22d to your computer and use it in GitHub Desktop.
Save omidnasri/e7a9f75e01d181955c4391b43566c22d to your computer and use it in GitHub Desktop.
jQuery.iframe.js,simple jQuery plugin for iframe element
/**
* Simple jQuery plugin for iframe element .
*
* Note: The parent doc and iframe's embed doc must be in the same origin ,
* Domains, protocols and ports must match.
*
* reference:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe
*
* @author manjun.han
* @date 2014.3.8
*/
(function($){
/**
* determine if the dom contained in jQuery wapper object is HTMLIFrameElement.
*
* @param {Object} The jQuery wapper object
* @return {Boolean} true,the dom is HTMLIFrameElement
*/
function validateIframe($el){
if($el.length == 0 || $el[0].nodeName.toLowerCase() != 'iframe'){
return false ;
}
return true ;
}
/**
* Get the window object of the HTML doc embed in iframe.
*
* @return {Object} window object of embed HTML doc.
*/
$.fn.iframeWin = function(){
return validateIframe(this) ? this[0].contentWindow : null ;
};
/**
* Get the document object of the HTML doc embed in iframe.
*
* @return {Object} document object of embed HTML doc.
*/
$.fn.iframeDoc = function(){
return validateIframe(this) ? (this[0].contentDocument || this[0].contentWindow.document) : null ;
};
/**
* Set the selected iframe element's height to its content doc's height.
*
* @return jQuery wapper object.
*/
$.fn.iframeAutoHeight = function(){
this.each(function(index , el){
var $el = $(el) ;
if(!validateIframe($el)){
return ;
}
var loaded = $el.data("iframe-loaded");
if(loaded){
$el.css("height" , $($el.iframeDoc()).height()+"px");
}else{
$el.bind("load" , function(){
$el.data("iframe-loaded" , true).iframeAutoHeight();
});
}
});
return this ;
};
})($);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment