我可以得到window.document
,但我怎样才能得到document.window
?我需要知道如何在所有浏览器中执行此操作。
6 回答
document.defaultView
如果您确定它是一个窗口并且可以在 IE 9 之前跳过 Microsoft 浏览器,则可以使用。
跨浏览器解决方案很复杂,以下是 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)
好吧,这就是我采用的解决方案。它有效,但我讨厌它。
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;
}
我选择DOCUMENT
从以下位置注入令牌@angular/platform-browser
:
import { DOCUMENT } from '@angular/platform-browser'
然后访问父级:
constructor(@Inject(DOCUMENT) private document: any) {
}
public ngOnInit() {
// this.document.defaultView || this.document.parentWindow;
}
首先让我们明确一点。当您使用框架、iframe 和多个窗口时,这种事情通常是必要的,因此如果您只能处理来自另一个窗口的文档而不是一个你在。
其次,不幸的是,没有直接的方法可以获取窗口对象。有间接的方法。
使用的主要机制是window.name。从某个父窗口创建窗口或框架时,通常可以给它一个唯一的名称。该窗口内的任何脚本都可以访问 window.name。窗口外的任何脚本都可以获取其所有子窗口的 window.name。
要获得比这更具体的信息,需要有关具体情况的更多信息。但是,在子脚本可以与父脚本通信或反之亦然的任何情况下,它们总是可以通过名称来识别彼此,这通常就足够了。
Window 对象是 JavaScript 层次结构中的顶级对象,因此只需将其称为 window
编辑:在促进 JS努力 之前的原始答案。Mozilla 开发者网络上的JavaScript 技术概述说:
在浏览器环境中,这个全局对象就是窗口对象。
编辑 2: 在阅读了作者对他的问题的评论(并获得了否决票)之后,这似乎与 iframe 的文档窗口有关。看看window.parent和window.top并可能比较它们以推断您的文档窗口。
if (window.parent != window.top) {
// we're deeper than one down
}