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

JavascriptIframe

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

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'];

Solution 3 - Javascript

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: https://stackoverflow.com/questions/38452697/what-is-the-proper-to-write-a-global-const-in-javascript-es6/51923076#51923076

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnkitView Question on Stackoverflow
Solution 1 - JavascriptJan PfeiferView Answer on Stackoverflow
Solution 2 - JavascriptAlain BeauvoisView Answer on Stackoverflow
Solution 3 - JavascriptPanu LogicView Answer on Stackoverflow