2012-06-28 51 views
1

我需要发送邮件(window.postmessage)到iframe。
目前它的工作,如果我有单页iframe内父页page.But我想使它适用于嵌套iframes。
指标分析如下:如何访问嵌套的iframe?

  • 我只能在最后一片叶子iframe中添加监听器代码。
  • 不知道iframe嵌套的长度。
  • 需要双向沟通,从父母到孩子也通过叶子iframe到父母。

我讨厌第三部分的iframe,请给我一些适当的解决方案。

+0

你是什么意思“我需要发送邮件到iframe”?你需要提交一个表单并将它[目标](http://dev.w3.org/html5/spec/attributes-common-to-form-controls.html#attr-fs-target)一个iframe?这不需要任何JS。 – zzzzBov

+0

不,soryy我没有正确解释,我打算了解https://developer.mozilla.org/en/DOM/window.postMessage。 – Debugger

回答

0

你可以实现一个事件系统,它自己向上或向下传播事件。

在所有iframe中添加这样的内容会将事件向下传播。

//create a jquery object to use the bind/trigger event system 
var vent = $({}); 

function trigger(event, args) { 
    //trigger for the current iframe 
    vent.trigger(event, args); 

    //propagate down for all nested iframes 
    $.each(getAllIframes(), function(i, iframe) { 
     iframe.trigger(event, args); 
    }); 
} 

function bind(event, callback) { 
    vent.bind(event, callback); 
} 

function getAllIframes() { 
    return $("iframe").map(function(){ 
     return this.contentWindow; 
    }); 
} 

可以实现事件以类似的方式冒泡,但必须有某种初始化逻辑的结合到所有子帧。

+0

我想你的方法对于获取同一页面中的所有帧非常有用。我需要知道帧内的帧数。 – Debugger