목표 : 웹브라우저에서 새로운 창을 띄우고, 새 창이 종료되면 원래 창에서 상품 현황을 다시 불러온다.
** 원래창 <-> 새창 간의 통신은 postMessage 사용.
1. 이슈 발생 : 태블릿에서 beforeunload 안의 소스가 전혀 실행되지 않아요
원래 소스)
let popWinObj = window.open("http://localhost:8080/myItemList.html");
popWinObj.onload = function() { //onload로 웹페이지가 로딩이 완료되면
popWinObj.onbeforeunload = function() {
//beforeunload로 브라우저 종료할 때만 함수 실행되도록 함.
... func ...
}
}
기존에는 새 창이 종료되기 직전 onbeforeunload event 로 제어하고 있었는데,
pc나 모바일에서는 가능했으나 태블릿에서 새창을 종료해도 원래 창에 아무 반응이 없었다.
이리저리 찾아보니 MDN에서 beforeunload 이벤트는 모바일에서 특히 불안정하다는 설명내용 발견
https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
Window: beforeunload event - Web APIs | MDN
The beforeunload event is fired when the current window, contained document, and associated resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.
developer.mozilla.org
2. 대안 - visibilitychange event
document 객체의 visibilitychange event 가 있었다.
현재 문서의 컨텐츠가 보여지거나(탭 활성화) 숨겨질 때(탭 비활성화)를 감지하여 작동한다.
또한 document.visibilityState 속성을 사용하면 현재 문서의 활성화 여부도 알 수 있으며,
document.visibilityState 속성값은 "visible" 또는 "hidden" 이다.
그래서 탭 활성화 여부에 따라 함수가 호출되도록 변경했습니다. 새창 종료하면 원래창이 활성화되니까요~
https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event
Document: visibilitychange event - Web APIs | MDN
The visibilitychange event is fired at the document when the contents of its tab have become visible or have been hidden.
developer.mozilla.org
사용 예시)
document.onvisibilitychange = function() {
... func ... //<- 이 부분에 onbeforeunload 에서 사용하던 함수 넣으면 작동한다.
}
적용하니 pc는 물론이고 태블릿, 모바일에서도 새창 종료했을 때 원래창 함수가 잘 작동했다.
끝!
< 참조글 >
Page Visibility API, 유저가 페이지를 보고 있는지 알려줘!
Page Visibility API 0. 들어가기에 앞서… 우리 서비스는 소켓 통신이 많이 발생한다. 그렇다보니, 유저가 다른 탭을 보고 있거나 페이지를 최소화했을 때는 소켓 통신을 비활성화 해야한다. 그런데
mong-blog.tistory.com
'웹개발지식쌓기' 카테고리의 다른 글
[IntelliJ] war 와 war exploded (0) | 2024.09.25 |
---|---|
[IntelliJ] IntelliJ + SVN + tomcat 연동 (0) | 2024.09.24 |
[back] List<Class> 256개 초과 시 저장되지 않는 오류 (1) | 2024.07.22 |
[IntelliJ] 폐쇄망에서 인텔리제이 라이센스 등록하기 (0) | 2024.02.08 |
[front] 브라우저 탭 아이콘 적용하기 (favicon) (0) | 2024.02.02 |