如何从其contentWindow引用iframe

How to reference the iframe from its contentWindow

本文关键字:引用 iframe contentWindow      更新时间:2024-04-29

如果我有iframe的contentWindow,我如何获得对该iframe引用。contentWindow是错误的目标。但是evt.target.parent只是给了我iframe所在的原始页面的窗口(至少我是这么认为的)。

我首先需要iframe,然后是iframe的容器(一个表),因为它包含我需要访问的另一个对象(一个文本区域)

    $.fn.setLine= function(target,errorline){
    var target=target;
    var codeLinesDiv = target.parent.parent.parent.find(".codelines");
    codeLinesDiv.children().eq(errorline).css("background-color","red");
    }

这将产生一个错误:未捕获的类型错误:对象#没有方法的子

如果我使用parent(),我得到:Uncaught TypeError:对象[object global]的属性'parent'不是函数(我不明白,为什么它不使用jQuery函数parent()?)

这就是我调用setLine函数的地方

   addIframeErrorListener= function(frame){
   handleError= function(evt){ 
   if(evt.message){   alert("error:"+evt.message+"  lineNo:"+ evt.lineno);
   $.fn.setLine(evt.target,evt.lineno);}
   }
   var win=(frame.contentWindow||frame.window);
   addEventListener.call(win,"error",handleError,true);
   }

所以我的问题是:如何从contentWindow到iFrame以及下一个包含它的容器

如果您的iframe和父页面来自不同的主机,则不允许iframe与父文档之间进行通信,因为这会造成很大的安全漏洞。

但是,如果iframe和parent来自同一个源(例如:http://mycoolpage.com/iframes和http://mycoolpage.com/parent)您可以使用parent.document.getElementById来获取所需的元素。