Search code examples
javascriptangulartypescriptangular-materialangular10

Angular: Show Material Popup before Closing Browser Window


I am trying to show Angular Material Dialog Box (Popup window), when User hits the Chrome Window Close button (upper right). The Dialog modal should hold prompt the user, if they want to save changes, or cancel,

However it only shows the modal for quick second, then closes without waiting for user. Using code reference below. How can it be fixed ?

How can we detect when user closes browser?

@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
    this.openDocumentSaveDialog();
}


public openDocumentSaveDialog(): void {
    const documentSaveDialogRef = this.documentSaveDialog.open(DocumentSaveDialogComponent, {
        width: '600px',
        height: '200px',
        disableClose: true,
        autoFocus: false,
        data: null
    });

    documentSaveDialogRef.afterClosed().subscribe(result => {
        this.closeMenu.emit()
    });
}  

enter image description here

Note: We do Not want to display Native chrome browser popup, but a custom popup .

Angular Material Dialog Box: https://material.angular.io/components/dialog


Solution

  • I am afraid that browser security won't allow you to prevent the user from closing the window. In my opinion this is not possible, you can only show the native window that warns the user about losing the data if closing the browser window.