同源策略 & iframe

Mariko Kosaka

在此代码实验室中,了解在访问 iframe 内的数据时同源策略是如何工作的。

设置:具有同源 iframe 的页面

此页面嵌入了一个 iframe,名为 iframe.html,在同源中。由于主机和 iframe 共享相同的来源,因此主机站点能够访问 iframe 内部的数据并像下方这样公开秘密消息。

const iframe = document.getElementById('iframe');
const message = iframe.contentDocument.getElementById('message').innerText;

更改为跨域 iframe

尝试将 iframesrc 更改为 https://other-iframe.glitch.me/。主机页面是否仍能访问秘密消息?

由于主机和嵌入的 iframe 没有相同的来源,因此对数据的访问受到限制。