Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a variable of iframe from parent

script of iframe

<script type="text/javascript" > var a=5; </script> 

script of parent window

<script type="text/javascript" > function close() { var check=document.getElementById("iframeid").contentDocument.a; alert(check) } </script> 

I want to access the variable which is defined inside the iframe from parent. But the above code doesn't work properly can anyone give an idea to implement this.

like image 870
Mirchi Avatar asked Dec 07 '12 06:12

Mirchi


People also ask

How do I get iframe from parent file?

To access elements of parent window from iframe with JavaScript, we can use the window. parent. document property to get the parent window's document.

How do I access iframe elements?

Getting the element in Iframeconst iframe = document. getElementById("myIframe"); Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe. const iWindow = iframe.

Can an iframe get parent URL?

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 !=

Can you interact with iframe?

All you have to do is first dispatch an event from the iframe to the parent that notifies the parent that the iframe is loaded (essentially a "ready message"). The parent will be listening for messages and if it receives the "ready message" event, it can then reply to the iframe with whatever message you want to send.


2 Answers

Using contentWindow instead of contentDocument works for me:

var check = document.getElementById("iframeid").contentWindow.a; 

Also, ensure that the domains match and that you are using a webserver to test (I got a protocol warning when testing from the file system).

UPDATE: You're almost definitely better to use the postMessage API.

like image 186
Lee Gunn Avatar answered Sep 19 '22 11:09

Lee Gunn


One method that has always worked reliably for me is for the iFrame to give its parent a reference to its own window when it first loads. The parent can then access all the variables through that reference. This does require that the parent is loaded before the iFrame, but for me that is usually the case.

So in the parent

var iFrameWin; 

Then in the iFrame at some point after it has loaded and settled down

parent.iFrameWin = window;  //parent now has a ref to the iframe's window 

Then, in the parent when it wants a global var contents from the iFrame

alert(iFrameWin.ivar);  // shows value if the global 'ivar' in the iFrame 
like image 38
John Page Avatar answered Sep 17 '22 11:09

John Page