Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set variable in parent window from iframe

I have a parent document with an embedded iframe. Inside the iframe I have an upload field. Once the user selects a file to upload, I trigger a jQuery change event. On that event I want to set a variable in the parent window to true, so that the parent knows that the upload has started.

Does anyone know how to do this?

Was trying this, but didn't work:

var test; $("#newsletter_email").change(function() {   parent.window.test = true;  });  $('#send').click(function() {     if (test) {         alert('File has been uploaded!');     } else {         alert('You need to upload a file');     } }); 
like image 828
Nic Hubbard Avatar asked Aug 19 '09 17:08

Nic Hubbard


People also ask

Can iframe access parent variables?

So, for instance, if you define a var myvar = 2 in the parent scope, you can access that in the iframe as window. parent. myvar.

Can iframe get URL of parent?

Yes, accessing parent page's URL is not allowed if the iframe and the main page are not in the same (sub)domain. However, if you just need the URL of the main page (i.e. the browser URL), you can try this: var url = (window. location !=

How do I turn off iframe parent window?

window. close(); or this: top. window. close(); you should be able to close it.


2 Answers

Variables in the global scope are auto-exposed as DOM properties of their containing window object.

This means that

var foo = 'bar'; 

is analogous to

window.foo = 'bar'; 

Which means that you can read the global scope of any window object you can obtain a reference to. What we can also imply here is that usage of window is implicit. Even when you don't explicitly type "window.", it's there anyway.

And since frames themselves are also auto-exposed as DOM properties of the current window object, this means you can access any other frames' window object as well.

The parent property of window objects holds a reference the window object of that window's parent (if there is one). Since iframes most certainly have a parent window, then all this stuff I just typed boils down to this

// set the global variable 'foo' in the parent global scope parent.foo = 'bar'; 
like image 79
Peter Bailey Avatar answered Sep 20 '22 00:09

Peter Bailey


You can also store it in the localStorage and read and write from it, provided that both the main document and the iframe share the same domain.

like image 26
Marta Avatar answered Sep 20 '22 00:09

Marta