Detect app close using global function

I need to call a query when app is closed using global function(beforeunload)
It works for other events like visibilitychnage, but not for beforeunload? caa i know why?

window.customApp=function(){
  return {
    onCloseQuery:null,
    userId:null,
    appId:null,
    activeWindow:true,
    
    init:function(query,userId,appId){
       this.userId=userId;
       this.appId=appId;
       this.onCloseQuery=query;

      
       document.addEventListener("beforeunload",()=>{
            this.activeWindow = !document.hidden;
            this.onCloseQuery.trigger({
              additionalScope:{
                appId:this.appId,
                userId:this.userId
              }
            });         
         }
       })
    }
    
  }
}()

There is a synxtax error. You are missing a ending ")". Please have a look at the screenshot below and let me know if that fixes it?

Also please I think following improvements can also be helpful.

  • Asynchronous operations: The beforeunload event doesn't wait for asynchronous operations like your query trigger to complete. By the time your query starts executing, the page might already be unloaded.
  • Event handler timing: Unlike visibilitychange, which allows time for operations, beforeunload has strict timing constraints.
  • Return value requirement: For beforeunload to properly work, you need to return a value from the handler.

Ahh. sorry i missed it when pasting it in this post. Nothing to do with bracket

ok thanks. is there any other way i can detect app close?

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

Thanks. This will work if i change tabs but not for tab close.

Can you give more context about the query? Like what is the exact feature you are trying to implement? I thinking of modifying our requirement or completely coming with a custom solution. So please can you explain more?

Currently we are blocked by:

  • Limited control: You cannot fully control the closing process.
  • Time constraints: Even with the confirmation dialog, the query execution time is limited. If your query takes too long, it still might not complete.
1 Like

Moving this to feature requests! Would love to hear more context as well :slight_smile: