Access a variable of iframe from parent

script of iframe

<script type="text/javascript" >
var a=5;
</script>

script of parent window

<script type="text/javascript" >
function close()
{
var check=document.getElementById("iframeid").contentDocument.a;
alert(check)
}
</script>

I want to access the variable which is defined inside the iframe from parent. But the above code doesn't work properly can anyone give an idea to implement this.


Using contentWindow instead of contentDocument works for me:

var check = document.getElementById("iframeid").contentWindow.a;

Also, ensure that the domains match and that you are using a webserver to test (I got a protocol warning when testing from the file system).

UPDATE: You're almost definitely better to use the postMessage API.


One method that has always worked reliably for me is for the iFrame to give its parent a reference to its own window when it first loads. The parent can then access all the variables through that reference. This does require that the parent is loaded before the iFrame, but for me that is usually the case.

So in the parent

var iFrameWin;

Then in the iFrame at some point after it has loaded and settled down

parent.iFrameWin = window;  //parent now has a ref to the iframe's window

Then, in the parent when it wants a global var contents from the iFrame

alert(iFrameWin.ivar);  // shows value if the global 'ivar' in the iFrame

script of iframe:

var a = 5;
window.parent.postMessage(['varA', a], '*'); // put this in some sort of function, ready, or whatever - you can call it multiple times if you need to as the code in the parent is an eventListener

script of parent window:

var b;
// you might want to write these into if statements to make sure that e.data[0] is varA if you have multiple messages coming across
if (typeof window.addEventListener != 'undefined') {
    window.addEventListener('message', function(e) {
        b = e.data[1];
    }, false);
} else if (typeof window.attachEvent != 'undefined') { // this part is for IE8
    window.attachEvent('onmessage', function(e) {
        b = e.data; // you'll probably have to play around with this part as I can't remember exactly how it comes across in IE8 -- i think it will involve slice() iirc
    });
}

Most of my knowledge on this topic comes from Ben Vinegar's talk on Seamless iFrames

This is a cross-domain "okay" method to deal wit this stuff. I'm sure there are some security holes, just as with anything on the web.