2009-08-27 39 views
44

我可以得到window.document,但我怎样才能得到document.window?我需要知道如何在所有浏览器中执行此操作。如何从Document对象获取Window对象?

+2

敢问我为什么?窗口是一个始终可用的对象,并且窗口中总是不会超过1个文档,可以说是1-1关系... – Colin 2009-08-27 00:10:50

+4

因为我在多个iframe中使用原型,并且各种Element方法在IE中断裂或Safari如果元素以某种方式在错误的范围内扩展。我已经修改了一些东西来解决原型中的这个问题,但修复程序的一部分需要我找到一个元素所在的窗口。 – Joren 2009-08-27 18:19:44

+0

@Joren,请考虑更改为接受的答案。 – kay 2016-02-09 15:41:27

回答

-1

The Window object is the top level object in the JavaScript hierarchy,所以才称它为窗口

编辑:前 原来的答复Promote JS努力。 JavaScript technologies overview在Mozilla开发者网络上说:

在浏览器环境中,这个全局对象是窗口对象。

编辑2: 阅读作者的评论对他的问题(并获得downvotes),这似乎与iframe的文档窗口后。看看window.parentwindow.top,并可能比较它们以推断您的文档窗口。

if (window.parent != window.top) { 
    // we're deeper than one down 
} 
+7

在open()之后,新窗口的'window'是另一个'window',而不是'opener'。如果您从某个函数接收到“文档”(或任何“节点”),则可能需要原始窗口。 (哇,这是非常古老的。) – Rudie 2013-03-21 18:08:55

77

您可以document.defaultView去,如果你确定它是一个窗口,它的好IE 9

+6

是的。请记住,根据规范,'document.defaultView'不必与'window'是同一个对象(事实上,它在一些较老的客户端中是不同的,例如:Safari 2.x) – kangax 2009-08-27 02:40:35

+0

适用于XUL文档在Firefox也!谢谢:) – macguru2000 2015-06-26 18:21:55

+1

doc.parentWindow || doc.defaultView,它在旧的IE和Safari – 2017-05-31 12:12:07

3

好之前跳过微软的浏览器,这是我去解决。它有效,但我讨厌它。

getScope : function(element) { 
    var iframes = top.$$('iframe'); 
    var iframe = iframes.find(function(element, i) { 
     return top[i.id] ? top[i.id].document == element.ownerDocument : false; 
    }.bind(this, element)); 
    return iframe ? top[iframe.id] : top; 
} 
+0

只有IE浏览器... – 2009-08-28 17:53:08

+0

什么是IE浏览器只有它?似乎在FF \ Saf \ IE \ Chrome中正常工作。 但是,除了IE之外,它不是必需的,因为其他浏览器都会在正确的范围内自动扩展元素。 – Joren 2009-08-31 23:15:10

17

一个跨浏览器的解决方案是复杂的,这里的道场是怎么做的(从window.js ::得到()):

// In some IE versions (at least 6.0), document.parentWindow does not return a 
// reference to the real window object (maybe a copy), so we must fix it as well 
// We use IE specific execScript to attach the real window reference to 
// document._parentWindow for later use 
if(has("ie") && window !== document.parentWindow){ 
    /* 
    In IE 6, only the variable "window" can be used to connect events (others 
    may be only copies). 
    */ 
    doc.parentWindow.execScript("document._parentWindow = window;", "Javascript"); 
    //to prevent memory leak, unset it after use 
    //another possibility is to add an onUnload handler which seems overkill to me (liucougar) 
    var win = doc._parentWindow; 
    doc._parentWindow = null; 
    return win; // Window 
} 

return doc.parentWindow || doc.defaultView; // Window 

有( “IE”)返回IE真(和否则为假)

0

首先让我们来清楚。当你使用框架,iframe和多个窗口时,这种事情通常是必要的,所以“窗口就是全局对象”是一个令人不满意的答案,如果你有一个句柄是另一个窗口的文档比你所在的地方还要多。

秒,遗憾的是没有直接获取窗口对象的方法。有间接的方式。

使用的主要机制是window.name。从某些父窗口创建窗口或框架时,通常可以给它一个唯一的名称。该窗口内的任何脚本都可以在window.name中获得。窗口外的任何脚本都可以获取其所有子窗口的window.name。

要获得更具体的比那需要更多的信息关于具体情况。但是在任何情况下,子脚本都可以与父脚本进行通信,反之亦然,它们总是可以通过名称来识别对方,而这通常就足够了。