Search code examples
angularfirebasengrxngrx-effects

Can I Dispatch NgRX Action & Effect before Browser/Tab is closed?


I'm using firebase cloud to store data of the user. For sake of argument let say is their favorite movies out of a list. Now, upon using the free firebase tier I don't want to make writes to the fire-cloud every time the user marks a movie as their favorite.

My intension is to update the data in the cloud once the user either logs out(which I already know how to do) or closes the browser || tab.

Is it possible to dispatch an action before or while the process of closing a browser/tab is happening?

Is there an alternative approach for this behavior?


Solution

  • Yes, you should leverage window:beforeunload event, accordingly to MDN :

    The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.

    This is typically what I do in the CoreComponent of my apps when needed :

      @HostListener('window:beforeunload', ['$event'])
      beforeunloadHandler(event) {
        this.store.dispatch(SomeActions.fireTheAction());
      }