본문 바로가기

FE/Vanilla

자바스크립트에서 네이티브 웹뷰가 닫혔을 때 감지

프로덕트에서 다음과 같은 이슈가 있었다.

 

--- Webview Stack ---
B Webview

A Webview

-----------------------

 

A, B Webview 는 별개의 영역 (크롬으로 치면 다른 탭) 이므로, 
최상단 B Webview 에서 행동한 결과에 대해 A Webview 가 인지할 수 없었다.

 

전에는 이런 상황에서 WebSocket 으로 시도를 하거나,

네이티브 개발자분들께 화이트리스트를 추가하는 방식을 말씀을 드렸었다. (네이티브에서는 웹뷰가 닫히는 것에 대해 감지가 가능)

이번 경우는 B Webview 에서의 행동은 POST 였고,

좋은 API 를 알게되어 적용하게 되었다.

window.addEventListener('visibilitychange', () => {
      window.location.reload();
    });

A Webview 페이지에 다음과 같은 코드를 추가하여
새로고침을 통해 GET 요청을 다시하여, 데이터를 유기적으로 업데이트할 수 있었다. 

참고 : https://developers.google.com/web/updates/2018/07/page-lifecycle-api#event-visibilitychange

 

Page Lifecycle API  |  Web  |  Google Developers

The Page Lifecycle API brings app lifecycle features common on mobile operating systems to the web. Browsers are now able to safely freeze and discard background pages to conserve resources, and developers can safely handle these interventions without affe

developers.google.com

이외에도 다양한 브라우저 API 들이 존재한다. 
윈도우 탭 이외의 곳을 선택하였다거나? 다른 탭을 이동하거나 등등 ..

브라우저의 라이프사이클도 중요한 개념인 것 같다.