在 <iframe>
的 JavaScript 中我需要在父窗口中调用一个函数。两个窗口都来自同一个域。
使用安全吗window.parent.myFunction();
?
最佳答案
简答
是的,您可以使用同一域中的 window.parent
。
WhatWG specification chapter 6: Loading Web pages说:
iframe.parent
存在iframe.parent
是iframe
父级 DOM 的代理- 如果来源相同则允许访问
真的很长很长的回答
我试图向您展示如何通过阅读规范得出这个结论,同时牢记:从 中访问
?parent
的特征是什么>iframe
让我们开始吧。这是一个很长的文本。
1。 DOM 属性 parent
WhatWG#dom-parent说到 window.parent
:
The parent IDL attribute on the
Window
object of aDocument
in a browsing context b must return theWindowProxy
object of the parent browsing context, if there is one (i.e. if b is a child browsing context), or theWindowProxy
object of the browsing context b itself, otherwise (i.e. if it is a top-level browsing context or a detached nested browsing context).
parent
是一个属性,用于访问父窗口的 DOM 之类的东西。然而:
- 什么是浏览上下文?
WindowProxy
有什么作用?
让我们继续阅读。
2。浏览上下文
浏览上下文是一种将 Document
对象呈现给用户的环境。
A tab or window in a Web browser typically contains a browsing context, as does an iframe or frames in a frameset. Each browsing context has a corresponding WindowProxy object.
3。窗口代理
窗口代理是一个代理window
对象并执行例如安全约束的对象。对于 window
对象,可以有多个代理(例如来自两个不同域的两个 iframe
访问同一父级)。
The WindowProxy object allows scripts to act as if each browsing context had a single Window object, while still keeping separate Window objects for each Document.
4。安全
我们快到了。继续阅读。
A browsing context A is allowed to navigate a second browsing context B if one of the following conditions is true:
- Either the origin of the active document of A is the same as the origin of the active document of B, or
- The browsing context A is a nested browsing context with a top-level browsing context, and its top-level browsing context is B, or
- The browsing context B is an auxiliary browsing context and A is allowed to navigate B's opener browsing context, or
- The browsing context B is not a top-level browsing context, but there exists an ancestor browsing context of B whose active document has the same origin as the active document of A (possibly in fact being A itself).
5。扣除
iframe
是否可以从其 parent
访问函数,如果它们都来自同一域?让我们推断。
parent
不是 parent 的window
对象,而是一个WindowProxy
。iframe
的浏览上下文可以访问其父级,因为它们具有相同的来源(参见上面的第一个安全条件)。
你看:如果你仔细阅读规范,你可以找到浏览器应该如何表现的答案。阅读规范是一种后天习得的技能。它需要耐心和精确。
然而:世界并没有那么美好。有些浏览器没有按照应有的方式实现规范。 买者自负。
关于javascript - 在 iframe 中使用 window.parent.myFunction 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12960494/