Search code examples
onbeforeunloadaurelia

Aurelia popup when refreshing the page not working


As we know, we can put a pop up asking if we are sure about refreshing the page when we click the refresh button on the browser. Usually it is done by adding an event listener on onbeforeunload.

However, in my Aurelia application, I try to do that but it's not working.

let's say this is my app.js ( root ModelView )

export class App {

this.refreshClicked = () =>{ return "Are you sure you want to exit?"; };

attached(){
window.addEventListener("onbeforeunload", this.refreshClicked);
}

But it is not working, however, if we replace the return statement to console.log("clicked") I can see that the listener works without any problem.

Any help?


Solution

  • First of all, if you are adding event handler through window.addEventListener, you don't use on prefix in that case. So it's either:

    attached() {
        window.addEventListener('beforeunload', this.refreshClicked);
    }
    

    or an older, not recommended, syntax:

    attached() {
        window.onbeforeunload(this.refreshClicked);
    }
    

    Second, you'll need to set the returnValue property on Event object and also return the same string value to support more browsers. To learn more about this event (and various browser quirks), check out its MDN page.

    Your refreshClicked should look like this:

    this.refreshClicked = e => {
        const confirmation = 'Are you sure you want to exit?';
        e.returnValue = confirmation;
        return confirmation;
    };