Inject javascript function into parent window from

2019-07-28 15:12发布

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?

5条回答
▲ chillily
2楼-- · 2019-07-28 15:37

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.

查看更多
老娘就宠你
3楼-- · 2019-07-28 15:41

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();
查看更多
小情绪 Triste *
4楼-- · 2019-07-28 15:49

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.

查看更多
放荡不羁爱自由
5楼-- · 2019-07-28 15:55

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);
查看更多
兄弟一词,经得起流年.
6楼-- · 2019-07-28 16:03

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

查看更多
登录 后发表回答