Javascript

JavaScript - 간단하게 새 창과 소통하는 Broadcast Channel API

개발따라김양 2024. 11. 8. 12:46

1. 문제 상황

  • A 화면과 B화면을 연동해서 A화면 이벤트 발생할 경우를 감지해 B화면에서 이벤트를 발생시켜야 했습니다.
  • 처음에는 childWindow를 이용했으나 부모 윈도우에서 다른 페이지 이동시 소통이 끊어지는 이슈가 발생했습니다.

2. 해결 방법

  • Broadcast Channel API를 활용해서 연결하면 다른 페이지로 이동할 경우에도 상관없이 연결이 지속됩니다.
const bc = new BroadcastChannel("test_channel"); //채널 연결

bc.postMessage("This is a test message."); // 메시지 전송

bc.postMessage({						// 딕셔너리 형태도 전송 가능
	 dog : "rive"
});


bc.onmessage = (event) => {   //메시지 받는 코드, event.data에 전송된 메시지 확인 가능
  console.log(event);
};



bc.close(); // 채널 떠나는 함수 ->  기본 채널에서 분리되어 가비지 수집 허용됨

 

 

 

 

참고 출처 : https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API

 

Broadcast Channel API - Web APIs | MDN

The Broadcast Channel API allows basic communication between browsing contexts (that is, windows, tabs, frames, or iframes) and workers on the same origin.

developer.mozilla.org