1

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.

DeepSpace101
  • 13,110
  • 9
  • 77
  • 127
  • I never used this but seem to be a jQuery plugin to support even old browsers: http://archive.plugins.jquery.com/project/postmessage – HMR Jun 29 '13 at 01:41

2 Answers2

2

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?

Community
  • 1
  • 1
Khanh TO
  • 48,509
  • 13
  • 99
  • 115
1

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);
Ansikt
  • 1,442
  • 11
  • 13