Inject javascript function into parent window from

2019-07-28 15:05发布

问题:

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?

回答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.



回答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();


回答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.



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


回答5:

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