user13889515
user13889515

Reputation:

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

Upvotes: 0

Views: 10352

Answers (3)

This works for me. But you have no control over the display!

@HostListener('window:beforeunload', ['$event'])
  showAlertMessageWhenClosingTab($event) {
      $event.returnValue = 'Your data will be lost!';
  }

Upvotes: 0

user4664714
user4664714

Reputation:

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.

Upvotes: 0

Ibrahim Rahhal
Ibrahim Rahhal

Reputation: 331

The beforeunload event doesn't support a callback function that returns a promise so you can't show the popup and return value as it isn't a sync operation.

what you can do instead is just returning false always or call

event.preventDefault()

and if the user decided to leave the page you can call

window.close(....)

if not you already have cancelled the event.

so your code should look something like this

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


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

    documentSaveDialogRef.afterClosed().subscribe(result => {
        if(!result)
           window.close()
        this.closeMenu.emit()
    });
}

Upvotes: 1

Related Questions