주의: allow-scripts와 allow-same-origin을 함께 쓰면 sandbox 보안이 무력화될 수 있습니다.
부모 ↔ iframe 간 통신 (postMessage)
iframe은 별도의 브라우징 컨텍스트이므로, 부모 페이지와 직접 DOM 접근이 제한됩니다. window.postMessage API를 사용하면 안전하게 메시지를 주고받을 수 있습니다.
부모 → iframe 메시지 전송
<!-- 부모 페이지 --> <iframeid="myFrame"src="child.html"></iframe>
<script> const iframe = document.getElementById('myFrame'); iframe.addEventListener('load', () => { // 두 번째 인자: 수신 대상 origin 지정 ('*'는 모든 origin 허용) iframe.contentWindow.postMessage({ type: 'HELLO', data: '안녕!' }, 'https://child-domain.com'); }); </script>
iframe → 부모 메시지 전송
<!-- child.html (iframe 내부) --> <script> // 부모로 메시지 전송 window.parent.postMessage({ type: 'RESPONSE', data: '받았어요!' }, 'https://parent-domain.com'); </script>
메시지 수신
// 부모 또는 iframe 어느 쪽에서나 동일하게 사용 window.addEventListener('message', (event) => { // 반드시 출처(origin)를 검증해야 합니다! if (event.origin !== 'https://trusted-domain.com') return;
console.log('수신한 메시지:', event.data); });
보안 팁: event.origin 검증 없이 메시지를 처리하면 XSS 공격에 노출될 수 있습니다.
동일 출처(Same-Origin) iframe 직접 접근
부모와 iframe이 같은 출처(same origin) 인 경우, JavaScript로 직접 DOM과 변수에 접근할 수 있습니다.