Do chính sách cùng nguồn (Same-Origin Policy), chỉ có thể truy cập iframe.contentDocument hoặc iframe.contentWindow.document khi iframe và trang cha cùng origin (protocol, domain, port giống nhau).
Cách truy cập an toàn
<iframe id="myId" src="same-origin-page.html"></iframe>
<script>
const iframe = document.getElementById('myId');
// Đợi iframe load xong
iframe.addEventListener('load', () => {
try {
const doc = iframe.contentDocument || iframe.contentWindow.document;
if (doc) {
const bodyContent = doc.body.innerHTML;
console.log('Iframe body:', bodyContent);
}
} catch (e) {
console.error('Cross-origin access blocked:', e);
}
});
</script>
Cross-origin (khác domain) – Giải pháp
- postMessage: Giao tiếp an toàn hai chiều giữa parent và iframe.
- Parent gửi:
iframe.contentWindow.postMessage({type: 'GET_BODY'}, '*') - Iframe lắng nghe:
window.addEventListener('message', e => { if(e.data.type==='GET_BODY') e.source.postMessage(document.body.innerHTML, e.origin) }) - Yêu cầu kiểm soát được code của cả hai trang.
Lưu ý bảo mật
- Luôn bọc trong
try/catch– ném exception nếu cross-origin. - Kiểm tra
iframe.contentDocumenttồn tại trước khi truy cập. - Sandbox attribute:
<iframe sandbox="allow-scripts allow-same-origin">hạn chế quyền iframe.