22.01.04 TIL - iframe 통신
9829 단어 JavaScriptDOMDOM
자식 iframe에서 부모 html로 접근하기
도메인이 같을 경우
도메인이 같을 때 자식 iframe의 html에서 부모 html 로 접근하고 싶을때는 window.parent
키워드를 사용해서 접근할 수 있다.
parent.html
<body>
<div id="parent-id">부모</div>
<iframe id="iframe" src="./child.html"></iframe>
</body>
child.html
<body>
<script>
const parentId = window.parent.document.getElementById('parent-id').id;
console.log(parentId); // parent-id
</script>
</body>
도메인이 다를 경우
그러나 iframe의 도메인이 부모 도메인과 다를 경우 아래와 같은 에러가 발생한다.
Uncaught DOMException: Blocked a frame with origin "https://example/child.html" form accessing a cross-origin frame. at HTMLDocument
그래서 이럴 때는 다음과 같이 Window.postMessage 를 사용한다.
parent.html
<body>
<div id="parent-id">부모</div>
<iframe id="iframe" src="https://example/child.html"></iframe>
<script>
// 2번
window.addEventListener('message', () => {
const parentId = document.getElementById('parent-id').id;
document.getElementById('iframe').contentWindow.postMessage(parentId, '*'); // 3번
});
</script>
</body>
child.html
<body>
<script>
window.parent.postMessage(null, '*'); // 1번
window.addEventListener('message', (e) => {
console.log(e.data); // parent-id
}); // 4번
</script>
</body>
실행 순서는 아래와 같다.
- child.html 의 parent.postMessage 함수가 호출된다.
- parent.html 에 message 로 등록된 함수가 실행된다.
- 자식 iframe에 contentWindow로 접근하여 등록되어있는 postMessage 함수를 호출한다.
- child.html 에 message 로 등록된 함수가 실행된다.
Author And Source
이 문제에 관하여(22.01.04 TIL - iframe 통신), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@leehaeun0/220104-공부일기-iframe-통신저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)