Created
March 5, 2012 23:44
-
-
Save jorgepedret/1982122 to your computer and use it in GitHub Desktop.
Dynamic resizing of iframe in a different domain
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
$(function(){ | |
var parent_url; | |
// Create the hidden input field that will hold the parent_url variable. | |
$("form").append('<input name="parent_url" id="parent_url" />'); | |
// We check to see if location hash is empty. It should only go in here if you're using IE and after the form as been submitted. | |
if(document.location.hash == ""){ | |
var search = document.location.search, | |
id = "parent_url=", | |
hs_start = search.indexOf('parent_url'), | |
hs_end = search.indexOf('&product_service'); | |
// Get the parent URL from the URL parameters sent by the form | |
parent_url = decodeURIComponent( search.substr(hs_start + id.length, hs_end - id.length - 1) ); | |
} | |
// If location hash is not empty, then we just assign it to the variable parent_url | |
else{ | |
parent_url = decodeURIComponent( document.location.hash.replace( /^#/, '' ) ); | |
} | |
// We assign the value of the parent_url to the hidden input element. That way if document.location.hash is not accessible, it can be accessed | |
$("#parent_url").val(parent_url); | |
// This is the function that posts a message to the parent for it to resize the iframe | |
function setHeight() { | |
$.postMessage({ if_height: $('body').outerHeight( true ) }, parent_url, parent ); | |
}; | |
setHeight(); | |
// Update all the links to attach the parent url to the href attribute | |
$("a").each(function() { | |
$(this).attr("href", $(this).attr("href")+"#"+parent_url); | |
}); | |
}); |
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
$.receiveMessage(function(e){ | |
var h = Number(e.data.replace( /.*if_height=(\d+)(?:&|$)/, '$1')); | |
if(!isNaN(h) && h > 0 && h !== if_height){ | |
$("#iframe_id").height(if_height = h); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment