Last active
December 10, 2015 20:49
-
-
Save m0er/4491041 to your computer and use it in GitHub Desktop.
cross-domain iframe communication
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
// Reference | |
// http://benalman.com/projects/jquery-postmessage-plugin/ | |
// http://softwareas.com/cross-domain-communication-with-iframes | |
// Related My post | |
// http://wp.me/p12fxZ-dS | |
// Wrapper page | |
var iframeSrc = "http://embedded-website.com/foobar/page.html#" + encodeURIComponent(document.location.href), | |
$iframe = $("<iframe>").attr("src", iframeSrc).appendTo("#container"); | |
$.receiveMessage( | |
function(e) { | |
var urlParams = queryStringToJson(e.data); | |
var iframeHeight = Number(urlParams.height); | |
var iframeWidth = Number(urlParams.width); | |
$iframe.height(iframeHeight).width(iframeWidth); | |
}, | |
"http://embedded-website.com" | |
); | |
function queryStringToJson(queryString) { | |
var match, | |
pl = /\+/g, // Regex for replacing addition symbol with a space | |
search = /([^&=]+)=?([^&]*)/g, | |
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, | |
query = queryString, | |
urlParams = {}; | |
while (match = search.exec(query)) | |
urlParams[decode(match[1])] = decode(match[2]); | |
return urlParams; | |
} | |
// Inner page | |
var parentUrl = decodeURIComponent( document.location.hash.replace( /^#/, '' ) ) | |
function resize() { | |
$.postMessage( | |
{height: 1200, width:900}, | |
parentUrl, | |
parent | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment