在此 Codelab 中,您将了解同源政策在访问 iframe 内的数据时如何发挥作用。
设置:包含同源 iframe 的网页
此页面在同一源中嵌入了一个名为 iframe.html 的 iframe。
由于宿主网站和 iframe 具有相同的来源,因此宿主网站能够访问 iframe 中的数据,并公开如下所示的私密消息。
const iframe = document.getElementById('iframe');
const message = iframe.contentDocument.getElementById('message').innerText;
更改为跨域 iframe
请尝试将 iframe 的 src 更改为 https://other-iframe.glitch.me/。
宿主页面是否仍能访问该私密消息?
由于主机和嵌入式 iframe 的来源不同,因此对数据的访问受到限制。