Javascript,从iFrame访问框架集中的嵌套框架

时间:2013-07-10 22:18:45

标签: javascript html iframe frame

我在访问加载到iframe中的页面一部分的框架时遇到问题。框架嵌套在多个框架集中。

我的HTML看起来像这样:

<iframe name="sourceframe" src="siteindex.html">
    #document <-- this appears in the dom tree. Not sure if it's relevant.
        <html>
            <head></head>
            <frameset>
                ...other frames
                <frameset>
                    <frame name="targetframe" src="sitesubpage.html">
                        ...I want to access this frame and replace the contents with a different html page...
                    </frame>
                </frameset>
            </frameset>
        </html>
</iframe>

我已经阅读过类似的问题,其中没有一个解决方案我可以开始工作。

任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:7)

window.frames['sourceframe'].frames['targetframe'].location.href = 'new_html_page';

FF和Chrome仅在frames中收藏window,IE和Opera也在document中收藏。当你更正你的时间时,上面的代码可以工作(测试)。

尝试在更改href之前使用一些超时,或从#targetframe触发更改。您还可以将onload事件侦听器附加到iframe,并触发其中的更改。另外,您可以在关闭iframe标记之前放置创建body的脚本,然后您可以使用window.onload更改深度页面...

答案 1 :(得分:0)

您可以为frame元素添加name='targetframe' id='targetframe'并执行以下操作:

function E(e){
  return document.getElementById(e);
}
function getChildFrame(id){
  var t = E(id);
  var f = t.contentWindow || t.contentDocument;
  if(f.document)f = f.document;
  return f;
}
var tf = getChildFrame('targetframe');
tf.style.backgroundColor = '#007';

http://www.w3schools.com/jsref/prop_frame_contentwindow.asp

http://www.w3schools.com/jsref/prop_win_frames.asp

了解更多详情。当然,同源政策适用。换句话说,未经许可,您无法访问其他人的frame

顺便说一句,您也可以使用数字访问frames数组。