最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Inject javascript function into parent window from iframe - Stack Overflow

programmeradmin8浏览0评论

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?

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?

Share Improve this question asked Mar 2, 2012 at 19:17 ShadedShaded 17.9k8 gold badges40 silver badges62 bronze badges 1
  • possible duplicate of Set variable in parent window from iframe – James Montagne Commented Mar 2, 2012 at 19:23
Add a ment  | 

5 Answers 5

Reset to default 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.

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

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

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.

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

发布评论

评论列表(0)

  1. 暂无评论