如何从 Document 对象中获取 Window 对象?

问题描述 投票:0回答:6

我可以得到

window.document
,但我怎样才能得到
document.window
?我需要知道如何在所有浏览器中执行此操作。

javascript html document
6个回答
122
投票

如果您确定它是一个窗口并且可以跳过 IE 9 之前的 Microsoft 浏览器,您可以使用

document.defaultView


18
投票

跨浏览器的解决方案很复杂,下面是 dojo 是如何做到的(来自 window.js::get()):

// 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

has("ie") 为 IE 返回 true(否则为 false)


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;
}   

2
投票

我选择从

DOCUMENT
注入
@angular/platform-browser
令牌:

import { DOCUMENT } from '@angular/platform-browser'

然后访问父级:

constructor(@Inject(DOCUMENT) private document: any) {
}

public ngOnInit() {
  // this.document.defaultView || this.document.parentWindow;
}

0
投票

首先让我们说清楚。当您使用框架、iframe 和多个窗口时,这种事情通常是必要的,因此如果您只能处理来自 another window 的文档,那么“窗口只是全局对象”是一个不令人满意的答案比你所在的那个。

第二,不幸的是没有direct 获取窗口对象的方法。有间接的方法。

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

要获得比这更具体的信息,需要有关特定情况的更多信息。然而,在子脚本可以与父脚本通信或反之亦然的任何情况下,它们总是可以通过名称相互识别,这通常就足够了。


-6
投票

Window 对象是 JavaScript 层次结构中的顶级对象,因此只需将其称为 window

编辑: 促进 JS 努力之前的原始答案。 Mozilla 开发者网络上的 JavaScript 技术概述 说:

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

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

if (window.parent != window.top) {
  // we're deeper than one down
}
© www.soinside.com 2019 - 2024. All rights reserved.