简体   繁体   中英

Accessing JavaScript variable in an iframe, from the parent window on same domain

I am fairly new to JavaScript and I am trying to get value of a variable from an embedded iframe. I have resorted to basic testing to make sure I am getting the method right...

I have tried the common suggestions and everything returns 'undefined'. I want to use the variable in an onclick event.

In the iframe content I have stripped everything and just for testing have this:

<script>
var test = "test";
</script>

in the parent window I have done this:

<iframe src="iframe.html" id="iframe" width="200" height="100"></iframe>

<script>
var myVar = window.frames[0].window.test;
</script>
<a href="#" onclick='alert(myVar)' id="link">Click</a>

I have tried the options suggested here: grab global variable from an embedded iframe

Everything I do returns undefined... am I doing something fundamentally wrong?

Thanks in advance..

You are already executing the script when the <iframe> is still loading, so it's test is undefined . Either wait for the iframe's load event, or just get the variable when clicking:

<iframe src="iframe.html" id="iframe" width="200" height="100"></iframe>

<script>
var myFrame = window.frames[0].window;
</script>
<a href="#" onclick='alert(myFrame.test)' id="link">Click</a>

You're apparently not waiting for the frame's content to be loaded before accessing myVar . Chances are the <script> element in the frame has not yet been fetched or executed when you do that.

Try delaying the variable assignment until the frame's content is fully loaded:

<iframe src="iframe.html" id="iframe" onload="frameLoaded();" width="200" height="100"></iframe>

<script>
    var myVar;
    function frameLoaded() {
        myVar = window.frames[0].window.test;
    }
</script>

As an aside, since your question is tagged I would suggest you write something like:

<iframe src="iframe.html" id="iframe" width="200" height="100"></iframe>

<script>
    $("#iframe").on("load", function() {
        var myVar = this.window.test;
        $("#link").on("click", function() {
            alert(myVar);
        });
    });
</script>

try to use this

 <iframe src="iframe.html" id="iframe" onload="loader()" width="200" height="100">    </iframe>

<script>
    var myVar
    function loader(){
        myVar = window.frames[0].window.test;
    }
</script>
<a href="#" onclick='alert(myVar)' id="link">Click</a>

在旁边的解决方案中,我只想指出当你使用jquery onload事件处理函数并且你想要访问jquery“this”对象时,你必须使用$(this.attr)表示法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM