JavaScript
[Javascript] BroadcastChannel 를 사용해서 탭 간 메세지 주고받기
teamnova
2023. 6. 7. 12:00
728x90
BroadcastChannel 란?
같은 브라우저의 다른 windows, tabs, frames or iframes(in different windows, tabs, frames or iframes) 간의 통신을 할 때 사용하는 클래스입니다.
BroadcastChannel를 사용해서 탭 간 메세지를 주고받는 예제입니다!
postMessage() 를 사용해서 다른 탭의 BroadcastChannel 에 메세지를 전송하고,
onmessage event를 통해 다른 탭이 전송한 메세지를 받을 수 있습니다.
실행결과입니다.
전체 코드입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
// Example 라는 이름의 BroadcastChannel 을 생성.
const Channel = new BroadcastChannel('Example');
function SendMessage(){
// 입력한 문자를 가져와서
let element = document.querySelector("input");
let data = element.value;
// 본인을 제외한 다른 채널에 메세지를 전달합니다.
Channel.postMessage({type: data });
}
// 다른 채널에서 보낸 메세지를 받는 이벤트
Channel.onmessage = e => {
// 다른 채널에서 보낸 메세지를 화면에 출력합니다.
alert(e.data.type)
}
</script>
</head>
<body>
<input type="text">
<button onclick="SendMessage()">Message Send</button>
</body>
</html>
아래의 페이지를 참고해보시면 좋을 것 같습니다.
https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel