Detect app close using global function

window.myCustomCode = function() {
  return {
    activeWindow: true,
    init: function() {
      document.addEventListener("visibilitychange", () => {
        this.activeWindow = (document.hidden) ? false: true;
        console.log('active window state changed ', this.activeWindow)
      });
    }
  }
}();
window.myCustomCode.init();

Also here is the complete solution. I think this wil really help you.

Solution