javascript - 在 iframe 中使用 window.parent.myFunction 是否安全?

标签 javascript html

<iframe> 的 JavaScript 中我需要在父窗口中调用一个函数。两个窗口都来自同一个域。

使用安全吗window.parent.myFunction();

最佳答案

简答

是的,您可以使用同一域中的 window.parent

WhatWG specification chapter 6: Loading Web pages说:

  • iframe.parent 存在
  • iframe.parentiframe 父级 DOM 的代理
  • 如果来源相同则允许访问

真的很长很长的回答

我试图向您展示如何通过阅读规范得出这个结论,同时牢记: 中访问 parent 的特征是什么>iframe?

让我们开始吧。这是一个很长的文本。

1。 DOM 属性 parent

WhatWG#dom-parent说到 window.parent:

The parent IDL attribute on the Window object of a Document in a browsing context b must return the WindowProxy object of the parent browsing context, if there is one (i.e. if b is a child browsing context), or the WindowProxy 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 对象呈现给用户的环境。

WhatWG#Browsing context说:

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 访问同一父级)。

WhatWG#proxy-object说:

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。安全

我们快到了。继续阅读。

WhatWG#security-nav说:

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 访问函数,如果它们都来自同一域?让我们推断。

  1. parent 不是 parent 的 window 对象,而是一个 WindowProxy
  2. iframe浏览上下文可以访问其父级,因为它们具有相同的来源(参见上面的第一个安全条件)。

你看:如果你仔细阅读规范,你可以找到浏览器应该如何表现的答案。阅读规范是一种后天习得的技能。它需要耐心和精确。

然而:世界并没有那么美好。有些浏览器没有按照应有的方式实现规范。 买者自负

关于javascript - 在 iframe 中使用 window.parent.myFunction 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12960494/

相关文章:

html - 通过媒体查询将表列换行

javascript - 将 td 内容溢出到下一个 td 元素,而不在 HTML 表格中进行替换

javascript - 有没有办法检测溢出 y :auto has been triggered, 并因此创建弹出窗口?

javascript - 填写所有必需的输入后按钮滑动

html - Logo 图像溢出导航栏

C中的TCP服务器脚本可以与HTML5中的TCP客户端脚本通信

javascript - 我可以使用 "time on page"触发 adwords 转换吗?

javascript - Bootstrap 4 Navbar 示例卡在移动模式

javascript - 尝试订阅 Firebase Cloud Messaging 主题时出现错误

visual-studio - <img> 标签不能嵌套在 <a> 标签中