在本程式碼實驗室中,您將瞭解存取 iframe 內的資料時,同源政策如何運作。
設定:包含同源 iframe 的網頁
這個頁面在相同來源中嵌入 iframe,名為 iframe.html。由於主機和 iframe 來源相同,主機網站可以存取 iframe 內的資料,並公開機密訊息,如下所示。
const iframe = document.getElementById('iframe');
const message = iframe.contentDocument.getElementById('message').innerText;
變更為跨源 iframe
請嘗試將 iframe 的 src 變更為 https://other-iframe.glitch.me/。代管網頁是否仍可存取機密訊息?
由於主機和嵌入的 iframe 來源不同,因此資料存取權會受到限制。