57

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?

Ankit
  • 3,083
  • 7
  • 35
  • 59

3 Answers3

87

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>
Jan Pfeifer
  • 2,854
  • 25
  • 35
  • 12
    Thanks, just realized how bad I am with javascript :p – Ankit Oct 04 '11 at 11:28
  • Just be cautious when calling functions from the parent, when they refer to window or document, they use parent window or document, not the ones from the iframe. – Andrey Oct 30 '20 at 17:21
43

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'];
Alain Beauvois
  • 5,896
  • 3
  • 44
  • 26
19

Great answers above. Just to add, beware of this in ES6:

 <script>
 const my_var2 = 'hello world!';
 let   my_var3 = 'hello world!';
 </script>

If you use the above in the main page, you can not refer to either my_var2 or my_var3 in the iframe(s). You must use 'var' to accomplish that.

This is because "const, let, and class don't create properties on the global object".

SEE: What is the proper to write a global const in javascript es6?

Panu Logic
  • 2,193
  • 1
  • 17
  • 21
  • 2
    This is a great point, and after struggling in chrome for an hour 0_o - you may want to know this problem is the same in chrome. Why in the world did they recommend going from 'var' to 'let' when there are unresolved issues like this?! – TV-C-1-5 Jun 06 '23 at 03:44
  • Question , what if JS is ES module and we use export for let and const. could we import them into iframe's ES module and use them? – pref Aug 31 '23 at 16:26