同源政策和 iframe

Mariko Kosaka

在此 Codelab 中,您将了解在访问 iframe 内的数据时,同源政策会如何发挥作用。

设置:使用同源 iframe 的网页

此页面在同一源中嵌入了一个名为 iframe.htmliframe。 由于主机和 iframe 共享同一源,因此托管网站能够访问 iframe 内部的数据并像炸弹一样公开秘密消息。

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

更改为跨源 iframe

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

由于主机和嵌入的 iframe 不同,因此对数据的访问会受到限制。