如何从 Document 对象获取 Window 对象?
我可以获取 window.document
但如何获取 document.window
?我需要知道如何在所有浏览器中执行此操作。
I can get window.document
but how can I get document.window
? I need to know how to do this in all browsers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用
document.defaultView
< /a> 如果您确定它是一个窗口并且可以跳过 IE 9 之前的 Microsoft 浏览器。You can go with
document.defaultView
if you’re sure its a window and its okay to skip Microsoft browsers before IE 9.跨浏览器解决方案很复杂,dojo 是这样实现的(来自 window.js::get()):
has("ie") 对于 IE 返回 true(否则返回 false)
A cross browser solution is complicated, here's how dojo does it (from window.js::get()):
has("ie") returns true for IE (and false otherwise)
嗯,这是我采用的解决方案。它有效,但我讨厌它。
Well, this is the solution I went with. It works, but I hate it.
我选择从
@angular/platform-browser
注入DOCUMENT
令牌:然后访问父级:
I opted to inject the
DOCUMENT
token from@angular/platform-browser
:and then access the parent:
首先我们要明确一点。当您使用框架、iframe 和多个窗口时,这种事情通常是必要的,因此,如果您所处理的只是另一个文档,那么“窗口只是全局对象”是一个令人不满意的答案窗口比您所在的窗口要大。
第二,不幸的是没有直接方法来获取窗口对象。有间接的方法。
使用的主要机制是window.name。当从某个父窗口创建窗口或框架时,通常可以给它一个唯一的名称。该窗口内的任何脚本都可以获取 window.name。窗口外部的任何脚本都可以获取其所有子窗口的 window.name 。
要获得更具体的信息,需要更多有关具体情况的信息。然而,在任何情况下,子脚本可以与父脚本通信,反之亦然,它们总是可以通过名称来识别彼此,这通常就足够了。
first off let's be clear. this sort of thing is often necessary when you are working with frames, iframes, and multiple windows, and so "the window is just the global object" is an unsatisfying answer if all you have a handle to is a document from another window than the one you are in.
second, unfortunately there is no direct way of getting at the window object. there are indirect ways.
the primary mechanism to use is window.name. when creating a window or a frame from some parent window, you can usually give it a unique name. any scripts inside that window can get at window.name. any scripts outside the window can get at the window.name of all its child windows.
to get more specific than that requires more info about the specific situation. however in any situation where the child scripts can communicate with parent scripts or vice versa, they can always identify each other by name, and this is usually enough.
Window 对象是 JavaScript 层次结构中的顶级对象,因此只需引用它即可作为窗口
编辑:
推广 JS 工作之前的原始答案。 Mozilla 开发者网络上的 JavaScript 技术概述 说道:
编辑2:
在阅读了作者对他的问题的评论(并获得了反对票)后,这似乎与 iframe 的文档窗口有关。看看 window.parent 和 window.top 并可能比较它们以推断您的文档窗口。
The Window object is the top level object in the JavaScript hierarchy, so just refer to it as window
Edit:
Original answer before Promote JS effort. JavaScript technologies overview on Mozilla Developer Network says:
Edit 2:
After reading the author's comment to his question (and getting downvotes), this seems to be related to the iframe's document window. Take a look at window.parent and window.top and maybe compare them to infer your document window.