'DIsplay popup when user refresh the page in angular 8

I want to show popup when user refresh/close tab in angular 8. I used candeactivate gaurd but its working when I change the route but not when I refresh/close the tab. Is there any way which will work for refresh,close tab event.



Solution 1:[1]

The only way you can do it by showing the default confirmation popup. It will ask the user if he's sure that he want to leave and discard the changes of not. This can be done by listening to the beforeunload event.

window.addEventListener('beforeunload', function (e) {
  // Cancel the event
  e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
  // Chrome requires returnValue to be set
  e.returnValue = '';
});

You don't have the ability to customize the message, so it will show the default one for each browser.

Solution 2:[2]

`<script type="text/javascript">
   window.onbeforeunload = function () {
  return 'Are you really want to perform the action?';
 }

`

add this in index.html

Solution 3:[3]

Confirmation Alert before browser reloads (i.e on reload of tab or on closing of tab)

This can also be done by using HostListener from angular core

EXAMPLE :

import { HostListener } from "@angular/core";

@HostListener("window:beforeunload", ["$event"]) unloadHandler(event: Event) {
    event.returnValue = false;
}

NOTE:

Chrome: v51, Firefox: v44, Safari: v9, Edge: Never Supported, Opera: v38

Thanks,

This may help you or somebody else :-)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 yazantahhan
Solution 2 liza
Solution 3 Aman Kumar Gupta