웹 개발을 하다 보면 다른 탭으로 이동했다가 다시 작업 중이던 탭으로 돌아왔을 때에 특정 이벤트를 주어야 하는 경우가 있다.
document.visibilityState를 이용하면 간단하게 구현할 수 있다.
const onVisible = async function () {
if (document.visibilityState) {
// 페이지(탭) 활성화 시 동작
}
};
document.addEventListener('visibilitychange', onVisible);
참고:
https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState
Document.visibilityState - Web APIs | MDN
The Document.visibilityState read-only property returns the visibility of the document, that is in which context this element is now visible. It is useful to know if the document is in the background or an invisible tab, or only loaded for pre-rendering.
developer.mozilla.org
'JavaScript' 카테고리의 다른 글
이벤트 루프와 콜스택을 시각적으로 확인하는 방법 (1) | 2025.02.08 |
---|---|
[TypeScript] type vs interface 차이점 (0) | 2025.02.07 |
[JavaScript] 자바스크립트의 자료구조 Set과 Map (0) | 2022.06.02 |
[JavaScript] Node.js에서 nodemailer를 이용해 메일 보내기 (0) | 2022.02.07 |
[JavaScript] 자바스크립트 Promise.all() 메서드 활용하기 (0) | 2022.01.28 |