MutationObserver 사용하기 (DOM을 구독하여 알림 주기)

MutationObserver는 DOM 트리의 변경을 감지한다.

이를 사용하면 실시간으로 DOM의 변경을 감지하고, 처리할 수 있다.

 

 

⛄️ 예제

 

간단하게 댓글을 다는 HTML을 구현해보자.

그리고, 새로운 댓글이 추가될 때 마다 이를 MutationObserver로 감지해서 alert를 띄우는 예제를 구현해보기로 했다.

 

일단, 기본적으로 댓글을 추가하는 HTML과 자바스크립트를 작성해준다.

<div id="root">
  <h2>Comment List</h2>
  <div id="comments"></div>
  <div id="input_div">
    <input type="text" placeholder="write comments..." class="text_input"/>
    <button class="input_btn">add</button>
  </div>
</div>

 

const inputDiv = document.getElementById("input_div");
const textInput = document.getElementsByClassName("text_input")[0];
const inputBtn = document.getElementsByClassName("input_btn")[0];

inputBtn.addEventListener("click", () => {
  const text = textInput.value;
  if(!text) {
    return;
  }
  const addDiv = document.createElement('p');
  addDiv.innerText = text;
  inputDiv.appendChild(addDiv);
})

그리고, 이 예제에 이제 댓글 p태그가 input div에 추가될 때 MutationObserver는 이를 탐지하고 alert를 띄울 수 있도록 코드를 더 작성해주자.

// 옵션을 통해서 감지할 대상을 설정할 수 있다.
const config = { attributes: true, childList: true, subtree: true };

// 변경 감지 시 실행할 콜백 함수
const callback = (mutationList, observer) => {
  for (const mutation of mutationList) {
    if (mutation.type === "childList") {
      console.log("자식 노드가 추가되거나 제거됐습니다.");
      window.alert("댓글이 추가됨!"); // 알림 추가!
    } else if (mutation.type === "attributes") {
      console.log(`${mutation.attributeName} 특성이 변경됐습니다.`);
    }
  }
};

// 콜백 함수에 연결된 감지기 인스턴스 생성
const observer = new MutationObserver(callback);

// 설정한 변경의 감지 시작
observer.observe(inputDiv, config);

// 이후 감지 중단 가능
// observer.disconnect();

아래의 참고 문서를 작성하여 위와 같이 댓글이 추가되었을 떄 alert를 띄우는 코드를 작성할 수 있었다.

DOM에 어떤 변화가 있었는지에 따라서 다르게 처리할 수도 있기에 유용한 점이 많은 것 같다.

더 이상 감지 기능을 사용하지 않는다면, disconnect로 감지를 중단할 수 있다.

 

☄️ 참고 문서

https://developer.mozilla.org/ko/docs/Web/API/MutationObserver

 

MutationObserver - Web API | MDN

MutationObserver 인터페이스는 DOM 트리의 변경을 감지하는 기능을 제공합니다. DOM3 이벤트 명세의 일부였던 Mutation Events (en-US)를 대체합니다.

developer.mozilla.org