1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Prevent the Default Browser Dialog on Page Refresh and Display a Custom Popup Instead

Discussão em 'Angular' iniciado por AHAYDOUS Karima, Junho 3, 2025.

  1. I’m working on a web application (Angular 18) where I’ve implemented a custom popup (modal) that appears everytime the user attempts to refresh the page. However, whenever the page is refreshed, the default browser confirmation dialog also appears alongside my custom popup, which is not the intended behavior. I need to suppress the default browser dialog on page refresh and display my custom modal instead. enter image description here

    @HostListener('window:beforeunload', ['$event'])
    onBeforeUnload(event: BeforeUnloadEvent): void {
    if (this.hasUnsavedData()) {
    event.preventDefault();
    event.stopPropagation();
    this.showConfirmationModal = true;
    }
    }

    @HostListener('document:keydown', ['$event'])
    onKeyDown(event: KeyboardEvent): void {
    if (event.key === 'F5' ||
    (event.ctrlKey && event.key === 'r') ||
    (event.ctrlKey && event.key === 'F5')) {
    if (this.hasUnsavedData()) {
    event.preventDefault();
    event.stopPropagation();
    this.showConfirmationModal = true;
    this.pendingRefresh = true;
    }
    }
    }

    • Implemented event.preventDefault() and event.stopPropagation() in the beforeunload handler to suppress the default browser dialog.
    • Added keydown listeners to intercept refresh attempts (F5, Ctrl+R, Ctrl+F5) and trigger a custom modal instead.
    • Tested event.returnValue = '', but it still triggers the browser dialog.
    • Confirmed hasUnsavedData() correctly detects unsaved changes.
    • Verified behavior in Chrome, Firefox, Edge, where the default dialog still appears with slight message variations.

    Continue reading...

Compartilhe esta Página