Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing global javascript variable of a page with an iframe within that page

I have an scenario where in I have a page, which have <script> tag and some global javascript variables within that. I also have an iframe within that page and I want to have access of global javascript variables of the page in iframe.

Is it possible?, if yes, how can i do that?

like image 826
Ankit Avatar asked Oct 04 '11 11:10

Ankit


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 an iframe run JavaScript?

Calling a parent JS function from iframe is possible, but only when both the parent and the page loaded in the iframe are from same domain i.e. example.com , and both are using same protocol i.e. both are either on http:// or https:// .

Can we declare global variable in JavaScript?

Declaring Variable: A variable can be either declared as a global or local variable. Variables can be declared by var, let, and const keywords. Before ES6 there is only a var keyword available to declare a JavaScript variable.


2 Answers

Easily by calling parent.your_var_name in your iframe's script.

One condition: both pages (main and iframe's) have to be on the same domain.

main page:

<script>  var my_var = 'hello world!'; </script> 

iframe

<script>   function some_fn(){     alert(parent.my_var); //helo world!   } </script> 
like image 120
Jan Pfeifer Avatar answered Oct 04 '22 07:10

Jan Pfeifer


Not possible if the iframe and the main document are not in the same domain (due to cross domain security policy).

To bypass this limitation you can use cross domain messaging.

Possible if iframe an main document are in the same domain, you can access their global variables. There are object which belongs to the window object of the iframe or the main page.

Here is the code to access the iframe variable myvar from the main document (or an iframe) in a same domain :

document.getElementById('iframeid').contentWindow['myvar']; 
like image 20
Alain Beauvois Avatar answered Oct 04 '22 08:10

Alain Beauvois