我可以获取 window.document
,但如何获取 document.window
?我需要知道如何在所有浏览器中实现。
我可以获取 window.document
,但如何获取 document.window
?我需要知道如何在所有浏览器中实现。
如果你确定它是一个窗口并且可以跳过IE 9之前的Microsoft浏览器,那么你可以选择 document.defaultView
。
document.defaultView
不必与 window
是同一个对象(实际上在某些旧版客户端中,如 Safari 2.x 中,它们是不同的)。 - kangax跨浏览器的解决方案比较复杂,以下是 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") 返回 true 表示当前浏览器为 IE(否则返回 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;
}
我选择使用来自@angular/platform-browser
的DOCUMENT
令牌进行注入:
import { DOCUMENT } from '@angular/platform-browser'
然后访问父元素:
constructor(@Inject(DOCUMENT) private document: any) {
}
public ngOnInit() {
// this.document.defaultView || this.document.parentWindow;
}
Window对象是JavaScript层次结构中的顶级对象,因此只需将其称为window
编辑: 在Promote JS之前的原始答案。Mozilla开发者网络上的JavaScript技术概述说:
在浏览器环境中,这个全局对象是window对象。
编辑2: 在阅读作者对问题的评论(并获得了负评)后,似乎与iframe的文档窗口有关。查看window.parent和window.top,并将它们与您的文档窗口进行比较。
if (window.parent != window.top) {
// we're deeper than one down
}
open()
打开新窗口后,新窗口的 window
对象与原来的 opener
窗口的不同。如果你从某个函数接收到一个 document
(或任何 Node
),可能需要使用原始窗口。(哇,这是非常久远的内容了。) - Rudie