[postMessage, message 이벤트] iframe과 소통하기

이진우·2023년 10월 23일
0

브라우저에서는 iframe과 부모가 도메인이 다르다면 서로의 컨텐츠를 직접 조작할 수 없도록 막아 놨기 때문에 메세지를 통해 iframe과 부모 같의 정보를 교환할 수 있습니다.

✉️ iframe에서 부모로 메세지 보내기

  • 부모 컨텐츠에서는 메세지 이벤트 리스너를 등록합니다.
<script>
  window.addEventListener('message', e => {
  	console.log(e.data);
  });
</script>

<iframe src="https://someurl.com/"/>
  • 자식 컨텐츠에는 메세지 보내는 코드를 작성합니다. (postMessage)
<!--url: https://someurl.com/-->
<script>
  window.parent.postMessage('this will show on console log', '*'); // '*' for any domain
</script>

부모 컨텐츠에서 자식으로부터 받은 메세지가 콘솔창에 나타나는 것을 확인할 수 있습니다.
this will show on console log

profile
언젠가 보게 된다. 기록하자 😡🔥🔥

0개의 댓글