如何从另一个框架访问框架的文档对象?

How does one have access to frame's document object from another frame?

本文关键字:框架 文档 对象 访问 另一个      更新时间:2023-09-26

好的,我有一个包含框架集的页面。其中一个框架包含一个asp页面,其中包含一个用javascript编写的脚本。这个脚本需要能够访问包含在另一个框架(在框架集)内的asp页面的内容。下面是框架集代码的示例:

<frameset name="foo">
    <frame name="frame1" src="mydomain/path/of/the/page.asp">
    <frame name="frame2" src="mydomain/path/of/the/other/page.asp">

所以基本上,在frame1中包含的页面中的脚本试图访问frame2中包含的页面中的内容(更具体地说是试图插入一个DOM元素)。

两个帧都在同一个域(和子域)上,所以交叉脚本应该不是问题。我不能在脚本外编辑代码,所以我被迫使用框架。下面是我当前的代码:

//Ideally, I would like to make sure the page contained within frame2 is loaded before trying to access it's elements. I still need to figure that one out. 
$(document, window.parent).ready( function () {    
    //Assign id "foo" to frame2 using jQuery
    $('frame[name="foo"]', window.parent.document).attr("id", "foo"); 
    var doc;
    var testNode;
    var frmObj = window.parent.document.getElementById('foo'); 
    if (frmObj.contentDocument) { // DOM
        doc = frmObj.contentDocument;
    } 
    else if (frmObj.contentWindow) { // IE 
        doc = frmObj.contentWindow.document;
    }
    if (doc) {
        testNode = doc.createElement('div');
        testNode.Id = "testNode";
        doc.getElementByTagName('body').appendChild(testNode);
    }
});  

包含getElementByTagName的行在IE 10中抛出错误:

SCRIPT438:对象不支持属性或方法'getElementByTagName'

文档对象似乎没有任何名为getElementByTagName的方法。在这种情况下,可以说文档对象不存在,这是荒谬的,因为我在尝试调用它的方法之前已经测试了它的存在性。知道了所有这些,我们如何解决这个问题?

指出:

  • 我不能用另一个浏览器测试这个问题,因为所有页面需要的外部代码使用vbscript。
  • id "foo"被成功添加到frame2.

多谢!

HTML5不支持框架,如果你有一个正确的文档类型声明,你会看到一个空白页面。

无论如何,不需要使用jQuery,这是更简单的:对frameset窗口,你引用总是top,所有的框架窗口,你可以捕获与top.frame_name (id是不需要的),无论你想要引用他们。当你需要一个文档,它就在window对象下。在您的情况下:top.frame1.documenttop.document

还要注意,fooframeset的名称,而不是任何帧的名称。因此,$('frame[name="foo"]', window.parent.document).attr("id", "foo");没有做你所期望的。(或者可能只是文章中的一个错别字?)

这应该可以完成这项工作,尽管top可能在frame2中的body存在之前已经准备好了很长时间。

$(document, top).ready(function () {    
    var testNode,
        frmObj = top.frame2,
        doc = frmObj.document;
    if (doc) {
        testNode = doc.createElement('div');
        testNode.id = 'testNode';
        doc.body.appendChild(testNode);
    }
});