Forum Moderators: open

Message Too Old, No Replies

Easy Javascript Variable Question!

         

victorcordova

5:04 pm on Dec 15, 2004 (gmt 0)

10+ Year Member



How do I pull a variable form a child frame to the parent frame?

I have a page (a) and an iframe inside of that frame (b). I want to put a variable from b into a. How do I do such a thing?

StupidScript

10:56 pm on Dec 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Use the DOM, Luke (or victor), use the DOM ... (and welcome aboard!)

<frameset rows="*,*">

<frame name="fA" src="pageA.html">

<frame name="fB" src="pageB.html">

</frameset>

pageA.html:

<script>

var testA = "testtext";

</script>

pageB.html:

Text <iframe id="fB1" src="pageC.html">

pageC.html:

<script>

document.write("testA = "+top.fA.testA);

</script>

Note how I referenced the "top" window object, then it's child frame object "fA" which contains the variable I wanted to grab for use in the iframe'd doc.

victorcordova

6:00 pm on Dec 16, 2004 (gmt 0)

10+ Year Member



right. i understand the concept and am able to pull a variable at the child level, but i want to do the exact opposite.

say

var testA = "testtext";

is put in page C

page B contains page C in an iframe

Page A contains page B in an iframe

I want to call the variable testA from Page A

StupidScript

6:27 pm on Dec 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The only issue here is whether the variable has been set or not.

top.childRef.varName

works with any child of the top object.

You may need to burrow down a bit more, like:

top.childRef.grandchildRef.varName

to get at your iframe-within-a-frame.

As long as the objects exist and varName has been set, you can get at it.

I say it like this because if you want a page loading into the first frame to use a variable you will be defining in an iframe within the second frame, chances are the iframe will not have loaded/defined before the first frame, so the variable and/or the childRef will not yet exist, and you'll get an error in the first frame.

You may have success in the above situation by causing pageA's grab for the variable in pageC's iframe to wait until pageC's iframe has (probably) loaded, using a pageC.iframe.onload event or a pageA.setTimeout() or something.

Sometimes I put a function in pageA to grab the pageC variable, and then call to the function right after defining the variable:

pageA.html:

<script>

function getVar(varVal) {

thisvar = varVal;

}

</script>

pageC.html:

<script>

varName="somevalue";

top.fA.getVar(varName);

</script>

Of course, it really depends on what you are planning to use the variable value for. If it's supposed to do something like change the page title or something fundamental like that, you may need to devise a different way to define the variable in pageA without needing to wait for pageC.