Reputation: 181
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..
Upvotes: 12
Views: 24433
Reputation: 101
In the aside solution I just wanted to point out that when you use the jquery onload event handler function and you want to access the jquery "this" object you have to use the $(this.attr) notation.
Upvotes: 0
Reputation: 262919
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 jquery 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>
Upvotes: 9
Reputation: 398
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>
Upvotes: 3
Reputation: 664217
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>
Upvotes: 12