Ankit Ankit - 1 month ago 5
Javascript Question

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?

Answer

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>
Comments