Hostlistener beforeunload not working for navigation within Angular application

Discussão em 'Angular' iniciado por LukeC92, Novembro 22, 2024.

  1. LukeC92

    LukeC92 Guest

    I want a banner that says "Settings saved succesfully" to display on the home page of my application, but for it to stop displaying after the user navigates away from the home page. My solution to this is on the save-settings page set a variable settingsSavedSuccesfully in SESSION_STORAGE. The process of saving the settings takes the user back to the home page where the banner uses ngIF to check for settingsSavedSuccesfully. I thought I could then remove that variable when the window beforeunload event is triggered.

    I have attempted two ways of implimenting this. First is by adding it within the constructor of the home page

    constructor(
    ...
    @Inject(SESSION_STORAGE) private sessionStorage: StorageService,
    ) {
    window.addEventListener("beforeunload", (event) => {
    this.sessionStorage.remove("settingsSavedSuccesfully");
    });
    }


    The other is by adding this HostListener method at the bottom of the home page's TypeScript

    @HostListener("window:beforeunload", ["$event"])
    onPageClose(): void {
    this.sessionStorage.remove("settingsSavedSuccesfully");
    }


    Refreshing the page will cause either of these to trigger. However, if I navigate away from home, within the application, it seems like beforeunload is not triggered. I have tested this on Google Chrome and on Firefox. I am assuming this is something to do with it being a "single-page web application".

    stewdebaker's answer under a similar question implies that if things are "configured correctly" the Hostlistener should be able from "both in-app and external navigation at the same time". Does anyone know if there's something I need to configure to make HostListener and beforeunload behave in the way I want them to? Did I misunderstood stewdbebaker's answer?

    My Angular CLI is version 18.0.6 incase that's relevant.

    Continue reading...

Compartilhe esta Página