Skip to content Skip to sidebar Skip to footer

Inject Javascript Function Into Parent Window From Iframe

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'

Solution 1:

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.

Solution 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();

Solution 3:

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.

Solution 4:

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);

Solution 5:

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

Post a Comment for "Inject Javascript Function Into Parent Window From Iframe"