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.
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.
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.
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 !=
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With