Skip to content

Instantly share code, notes, and snippets.

@OdinsHat
Created May 20, 2015 11:25
Show Gist options
  • Save OdinsHat/43ff0fe3d4cd38f7a5f3 to your computer and use it in GitHub Desktop.
Save OdinsHat/43ff0fe3d4cd38f7a5f3 to your computer and use it in GitHub Desktop.
iframe PHP example passing an id to iframe getting hashed value back via postrmessage
<html>
<head>
<title>The IFrame</title>
</head>
<body>
<h1>IMAGINE THIS IS PRODUCT DESIGNR</h1>
<form id="form-pdesignr">
<input type="button" value="Click Me to Post Data Up ^" />
</form>
<script>
document.getElementById('form-pdesignr').addEventListener("click", function(){
parent.postMessage(
"Sent ID: <?php echo (int)$_GET['cid']; ?> Lets hash that for giggles: <?php echo md5((int)$_GET['cid']); ?>",
"http://othersite.com"
);
});
</script>
</body>
</html>
// Create IE + others compatible event handler
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
document.addEventListener("DOMContentLoaded", function(event) {
iframe = document.createElement("iframe");
iframe.setAttribute("src", "http://handylabels.localhost.com/iframe.php?cid=" + window.productdesignrClientId);
iframe.style.width = 900+"px";
iframe.style.height = 900+"px";
iframe.style.border = 1+"px solid #000";
document.getElementById('product-designr-script').parentNode.appendChild(iframe);
/**
* This listens to the evcent from the child iframe page
*/
eventer(messageEvent,function(e) {
document.getElementById('hash').value = e.data;
}, false);
});
<DOCTYPE html>
<html>
<head>
<title>The Parent Page</title>
</head>
<body>
<h1>Parent Page</h1>
<p>This is what will have the iframe embeded in it and receive the data via postMressage()</p>
<input type="value" name="hash" id="hash" style="font-size:20px;font-weight:bold;padding:10px;width:900px;"/>
<!-- WE GIVE THIS -->
<script type="text/javascript">
window.productdesignrClientId = 564;
</script>
<script type="text/javascript" src="http://othersite.com/pdesigner.js" id="product-designr-script"></script>
<!-- /WE GIVE THIS -->
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment