Reputation: 13722
We have two domains, domain.com
and sub.domain.com
On domain.com
<html>
<head>
<title>Main</title>
</head>
<body>
<h1>This is the parent</h2>
<iframe src="http://sub.domain.com/results.aspx"
width="100%" height="1px" id="iframe1">
</iframe>
</body>
</html>
Quesiton: How can we adjust the iframe height from 1px
to it's real height (when the iframe loads)? As the user plays in the iframe, it's height can change, so I suspect it might be needed to hook it to some event.
Now I'm fully aware that cross scripting is prevented in the browser and that even subdomains (or different port numbers) constitute "cross-domain". However, we control both the domains so I'm looking for a good solution for this. We looked at window.postMessage which seems to be designed specifically for this but couldn't make it work.
Upvotes: 1
Views: 1776
Reputation: 1552
What you're looking for is iframe message passing:
https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage
In the parent page:
var iframe = document.getElementById('myIframe');
function resizeIframe(event){
if (event.origin !== "http://example.org"){
// We trust this message
iframe.setAttribute("style", "width:" + event.data + "px;");
}
}
window.addEventListener('message', resizeIframe, false);
In the child page:
function postParent(){
window.postMessage($(body).height(), 'http://parentdomain.org');
}
$(window).on('load', postParent);
Upvotes: 1
Reputation: 48972
Your case is simple because it's cross-scripting subdomains (not cross-scripting different domains). Just assign document.domain = "domain.com"
in both your page and iframe.
For more information, check out:
Cross sub domain iframes and JavaScript and
How to communicate between frames?
Upvotes: 2