The onbeforeunload confirmation dialog is not displayed when angular2 @HostListener is used

Using the @HostListener binding, but confirming the dialog (which asks: do you want to leave this page? ... or do you want to reinstall it?) Is not displayed.

The code works, but the confirmation dialog is not displayed.

Here is what I have:

@HostListener('window:beforeunload', ['$event'])
public doSomething($event) {
    console.log("do I see this?") // <---- this logs to the console.

    return "something else";
}

But I do not see this:

enter image description here

+6
source share
4 answers

return falseinstead of a string "something else"fixes the problem and a confirmation dialog is displayed.

It is possible that angular bindings change the return value

+8
source

For those still looking for another way to handle this in Angular. You can try to do this:

<router-outlet (window:beforeunload)="doBeforeUnload()" (window:unload)="doUnload()"></router-outlet>

router-outlet, , app.component.html, . , beforeunload false, unload . , , , . :

doBeforeUnload() {
    // Alert the user window is closing 
    return false;
}

doUnload() {
    // Clear session or do something
    this.auth.getLogout();
}

PD: Angular 6.

+2

return $event.returnValue = "something";

. .

+1
source

Instead of returning, falseyou need to return$event.returnValue = "your text"

Modern browsers do not display the entered text.

@HostListener('window:beforeunload', ['$event']) 
yourfunction($event) {
    return $event.returnValue='Your changes will not be saved';
}
+1
source

Source: https://habr.com/ru/post/1015978/


All Articles