Angular 12: How to detect when a browser tab is closing and implement a confirmation dialog with MatDialog

I have a scenario where I am checking if the browser tab is closed using the code below. It currently works with windows dialog, but I would like to incorporate MatDialog for confirmation instead.

 @HostListener('window:beforeunload', ['$event'])
  beforeunloadHandler(event) {
    return false;
  }

I attempted the following code, however, it did not work as expected.

@HostListener('window:beforeunload', ['$event'])
  beforeunloadHandler(event) {
    this.iDialogData.title = 'Unsaved changes';
    this.iDialogData.bodyMessage = 'If you leave this page, any unsaved changes will be lost.';
    this.iDialogData.cancelBtnText = 'Cancel';
    this.iDialogData.mainbtnText = 'Leave page';
    const dialogRef = this.openDialog();

    return dialogRef.afterClosed().pipe(map(result => {
      if (result !== undefined)
        return true;
      else
        return false;
    }));
  }

Answer №1

If you're looking for a solution, consider exploring this approach:

@HostListener('window:beforeunload', ['$event'])
  beforeunloadHandler(event) {
    if (this.canClose) {
        return true;
    }

    this.iDialogData.title = 'Unsaved changes';
    this.iDialogData.bodyMessage = 'If you navigate away from this page, any unsaved modifications will be discarded.';
    this.iDialogData.cancelBtnText = 'Cancel';
    this.iDialogData.mainbtnText = 'Leave Page';
    const dialogRef = this.openDialog();

    dialogRef.afterClosed().subscribe(result => {
        if(result) { 
           this.canClose = true;
           // fire the event again
        }
    });
    return false;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Diving deep into the reasons behind a test's failure

Currently, I am using Postman to test the API that I am developing with express. In this process, I am creating a series of tests. Below is a brief example: tests["Status code is 200"] = responseCode.code === 200; // Verifying the expected board var expe ...

Filling a HTML div with data through PageMethods and AJAX

My issue is quite unique. Despite checking numerous examples before reaching out here, I am facing a peculiar problem. I have a div element in my ASPX file and I am using AJAX to send a POST request to populate it. <script> function send(input ...

Tips for avoiding unnecessary re-renders when using a functional component and react hooks:

Problem: When a user enters a room code in the input field, the web application re-renders, causing the socket to disconnect and reconnect. Scenario: I am developing a multiplayer game using technologies like Socket.io, React, Express, PostgreSql, and Nod ...

Facing a dilemma: Javascript not updating HTML image source

I am facing an issue while attempting to modify the source of my HTML image element. Despite using document.getElementId('image') in my code, I am unable to make it work as intended. Surprisingly, there are no errors displayed. Interestingly, whe ...

Is using global variables as a namespace a good practice? Creating ambient TypeScript definitions in StarUML

I'm currently working on creating TypeScript type definitions for the StarUML tool. While I've been successful in defining most of the API, I've hit a roadblock when it comes to linking a JavaScript global variable ("type" in this case) with ...

What is the best way to find the difference between two time moments using Moment

Hello everyone, I could really use some assistance with Moment.js. I have two input fields, one labeled Start and the other labeled Stop. start = moment().format('LT'); // This works when I click on the play button stop = moment().format(' ...

StorageLimit: A new condition implemented to avoid saving repetitive values in the localStorage

Is there a way to store the text of an li element as a localStorage value only once when clicked? If it already exists in localStorage, a second click should have no effect other than triggering an alert. I'm currently using an if statement inside a ...

steps to determine if a page is being refreshed

Is there a way to prevent the page from reloading when the user clicks the reload button in the browser? I attempted to use this code, but my break point is not triggering. ngOnInit() { this.router .events .subscribe((e: RouterEvent) = ...

Making requests using Axios in a web application created with Express, Node, and EJS

I'm currently working on a project that involves using Express.js, node.js, Axios, and ejs. The aim is to make REST calls to Oracle SQL REST services through Axios. However, I am facing challenges when it comes to dealing with Promises or Async/Await. ...

Troubleshooting problem in Java related to encoding with XMLHttpRequest

Currently, I am utilizing XMLHttpRequest for an ajax call to my server. Let's consider the call: http = new XMLHTTPRequest(); var url = "http://app:8080/search.action?value=ñ" http.open("GET",url,true); http.setRequestHeader("Content-type", "applica ...

Decoding request header in Angular during app initialization

Currently, I have three domain names registered with Godaddy and they are all directing to the same server that is hosting my Angular 2 application. I am curious if there is a method to examine the request header in order to identify which of the three d ...

Learn the process of triggering an Ajax request by clicking on a Table row

I am facing an issue with my table. Whenever I click on a row, the <TR> element gets assigned the class "selected". My goal is to capture the content of the first <TD> element in that row (which represents an ID), and then make an Ajax request. ...

Ensure menu options are aligned to the right using material-ui

My material-ui menu currently has the following setup: <span> <Link to="/issues"> <Button style={isActive(history, "/issues")}>Issues </Button> </Link> <Link to="/users"> <Button style={isActive(his ...

DiscoverField Component with Button Functionality and Checkbox Dilemma

I'm working with Vue 3, Vuetify, and TypeScript for my searchField component. Inside, I have two buttons: FreeItemMaster and PatternMaster. Clicking on these buttons should change their background color and display respective content below them. Howev ...

To close modal A in ReactJS using React-Bootstrap after opening modal B from modal A, follow these steps:

When the registration button is clicked, a signup modal appears. Is there a way to then open a login modal from within the signup modal, ensuring that the signup modal closes once the login modal pops up? show={this.props.signupModalOn} onHide={this.props. ...

Error Message: jQuery script imported successfully, however, functions are not defined

Here is my HTML code: <script type="text/javascript" src="js/myjs.js"></script> <script> ... $("#enviornment").hide().delay(1200).css({'display':'block', 'opacity':'0'}).animate({'opacity&apos ...

React splits the page and interrupts the scroll event listener

For some reason, my webpage has been split by the React.js library. When attempting to scroll down while hovering over the top navigation menu, scrolling becomes impossible. However, scrolling works fine when done on any other part of the screen. I' ...

Can you identify a specific portion within an array?

Apologies for the poorly titled post; summarizing my query into one sentence was challenging. I'm including the current code I have, as I believe it should be easy to understand. // Constants that define columns const columns = ["a", " ...

I am currently experiencing difficulties with uploading an image from the admin panel in Magento 1.9. Instead of receiving the expected response, I am

I encountered an error while trying to upload a file in Magento for a product image. When I click on upload, an error is displayed during the file upload process. Upon further investigation in the product.js file for item response, I noticed that HTML is b ...

Sort slider items using Show/Hide feature in bxSlider

I am using a bxslider on my website with specific settings: $('#carousel').bxSlider({ slideWidth: 146, minSlides: 2, maxSlides: 6, speed:500, adaptiveHeight: true, moveSlides:3, infiniteLoop : false, hideContr ...