Your generous donation allows me to continue developing and updating my code!
Note that both parent and child need to include the jQuery postMessage javascript, and for communication to be enabled in browsers that don't support window.postMessage, the child page must know the exact parent URL (in this example, that is done by passing the parent location into the Iframe using a hash param in the Iframe src attribute).
The parent window code
01.
$(
function
(){
02.
03.
// Keep track of the iframe height.
04.
var
if_height,
05.
06.
// Pass the parent page URL into the Iframe in a meaningful way (this URL could be
07.
// passed via query string or hard coded into the child page, it depends on your needs).
08.
src =
'http://rj3.net/code/projects/jquery-postmessage/examples/iframe/child/#'
+ encodeURIComponent( document.location.href ),
09.
10.
// Append the Iframe into the DOM.
11.
iframe = $(
'<iframe " src="'
+ src +
'" width="700" height="1000" scrolling="no" frameborder="0"><\/iframe>'
)
12.
.appendTo(
'#iframe'
);
13.
14.
// Setup a callback to handle the dispatched MessageEvent event. In cases where
15.
// window.postMessage is supported, the passed event will have .data, .origin and
16.
// .source properties. Otherwise, this will only have the .data property.
17.
$.receiveMessage(
function
(e){
18.
19.
// Get the height from the passsed data.
20.
var
h = Number( e.data.replace( /.*if_height=(\d+)(?:&|$)/,
'$1'
) );
21.
22.
if
( !isNaN( h ) && h > 0 && h !== if_height ) {
23.
// Height has changed, update the iframe.
24.
iframe.height( if_height = h );
25.
}
26.
27.
// An optional origin URL (Ignored where window.postMessage is unsupported).
28.
},
'http://rj3.net'
);
29.
30.
// And for good measure, let's send a toggle_content message to the child.
31.
$(
'<a href="#">Show / hide Iframe content<\/a>'
)
32.
.appendTo(
'#nav'
)
33.
.click(
function
(){
34.
$.postMessage(
'toggle_content'
, src, iframe.get(0).contentWindow );
35.
return
false
;
36.
});
37.
38.
});