1

I'm working on a project that has many iframes that are opened and closed in a parent window. I have an object that needs to be defined and shared between the iframes. The issue I'm running into is that when the iframe that created the object on top is closed the functions associated with it are lost.

Is there a way I can define an object on top that will be accessible from my iframes even after the original iframe goes out of scope?

Shaded
  • 17,276
  • 8
  • 37
  • 62
  • possible duplicate of [Set variable in parent window from iframe](http://stackoverflow.com/questions/1301540/set-variable-in-parent-window-from-iframe) – James Montagne Mar 02 '12 at 19:23

5 Answers5

3

We came across this problem and this question and eventually solved it by creating a script tag in the parent document's head.

So instead of

window.parent.myfunc = function(){...}

we did

var script = window.parent.document.createElement('script');
script.text = "var myfunc = function(){...}";
window.parent.document.getElementsByTagName('head')[0].appendChild(script);

A little ugly but it works.

wickning1
  • 91
  • 3
2

You can create a function by its constructor on parent window. In this case the reference of the function remain on the parent window and can be called from all iFrames

parent.func = new parent.Function('a','b','alert(a+b);');

It will be visible from every iFrame

parent.func(3,4);
Federico
  • 21
  • 1
2

You can declare the function as a member of the iframe's parent window:

window.parent.func = function() {alert("test")};

Them it will be visible to every iframe:

window.parent.func();
vdeantoni
  • 1,948
  • 14
  • 19
  • Hmm I've been trying something like this, but I'm getting "Can't execute code from a freed script" errors on the functions defined inside. I'm thinking there's something I'm missing. Thanks for the help! – Shaded Mar 02 '12 at 19:34
  • Thinking further on this, every iframe will only have access to the parent's reference to the javascript. So when the original iframe is closed the javascript will be lost. – Shaded Mar 05 '12 at 21:25
1

In case someone else stumbles across this. What I've found is that Javascript functions are stored as references, so defining top.func = function(){...} from an iframe will create a reference to the function on the top. This means that if the iframe is lost so is the function.

My solution was to create an iframe that's hidden in the background and created when that function needs to be defined.

Shaded
  • 17,276
  • 8
  • 37
  • 62
0

One solution may be passing them using query string of src of iframe, or store the object in server session.

Reza Owliaei
  • 3,293
  • 7
  • 35
  • 55